text:
#include <IOKit/IOLib.h>
#include <IOKit/IOBufferMemoryDescriptor.h>
#include <IOKit/graphics/IOGraphicsInterfaceTypes.h>
#include "EWProxyFrameBufferClient.h"
#include "EWProxyFrameBuffer.h"
#include "EWProxyFrameBufferDriver.h"

//I didn't have time (yet) to implement an interrupt management
//therefore i rely upon the already available implementation from apple.
//but... you can't fire these interrupts without this macro and the presence
//of a private header (part of the project).
#define IOFRAMEBUFFER_PRIVATE
#include "EWProxyFrameBufferFBuffer.h"
#undef IOFRAMEBUFFER_PRIVATE

extern "C" {
#include <pexpert/pexpert.h>//this is for debugging only
}

#define kIOPMIsPowerManagedKey          "IOPMIsPowerManaged"

#define super IOFramebuffer

OSDefineMetaClassAndStructors(info_ennowelbers_proxyframebuffer_fbuffer, IOFramebuffer)

#pragma mark Functions used by user space
//all these functions are called indirectly due to a running user space application

IOReturn info_ennowelbers_proxyframebuffer_fbuffer::Connect(int mode)
{
	if(connected)
		return kIOReturnStillOpen;
	else
	{
		EWProxyFramebufferModeInfo info;
		//first we need to get the mode in order to tell OS about it.
		int ret=fProvider->getmodeInfo(mode, &info);
		if(ret!=kIOReturnSuccess)
			return kIOReturnBadArgument;
		this->mode=mode;
		IOLog("EWProxyFrameBuffer: mode is now %d\n",mode);
		//helper variables for disconnect and in order to prepare mode switch without
		//disconnecting (i think).
		connected=true;
		warmup=true;
		//this call is the reason for the private header
		connectChangeInterrupt(this,0);
		return kIOReturnSuccess;
	}
}

IOReturn info_ennowelbers_proxyframebuffer_fbuffer::Disconnect()
{
	if(connected)
	{
		connected=false;
		//tell OS that we have no screen.
		connectChangeInterrupt(this,0);
		return kIOReturnSuccess;
	}
	else
	{
		return kIOReturnNotOpen;
	}
}

IOReturn info_ennowelbers_proxyframebuffer_fbuffer::State()
{
	if(!connected)
		return 0;
	else
		return mode;
}

//this function is left behind.
//i wanted the framebuffer to be able to switch resolution from our client
//(not from OS side), but it was not possible. OS ignores resolutions switches
//other than those originating from OS. It is Borg.
void info_ennowelbers_proxyframebuffer_fbuffer::SwitchResolution()
{
	if(warmup)
	{
		handleEvent(kIOFBNotifyDisplayModeWillChange, NULL);
		handleEvent(kIOFBNotifyDisplayModeDidChange, NULL);
		warmup=false;
	}
}

#pragma mark Framebuffer functions
//This Function is used by OS to fetch driver capabilities.
//The only thing we support is a hardware cursor
IOReturn info_ennowelbers_proxyframebuffer_fbuffer::getAttribute( IOSelect attribute, uintptr_t * value )
{
	union myvar
	{
		IOSelect attribute;
		char param[5];
	};
	myvar var;
	var.attribute=attribute;
	var.param[4]='\0';
	IOLog("EWProxyFrameBuffer: getAttribute(%s).\n",var.param);
	IOReturn ret= super::getAttribute(attribute, value);
	if(attribute==kIOHardwareCursorAttribute)
	{
		*value=1;
		ret= kIOReturnSuccess;
	}
	if(value!=NULL)
		IOLog("EWProxyFrameBuffer: Value= %x, Ret=%x\n",(unsigned int)*value,ret);
	else
		IOLog("EWProxyFrameBuffer: Ret=%x\n",ret);
	return ret;

}

//This Function is used by OS to command the driver.
//the important ones:
//CAPTURE: during bootup at a certain point AQUIRE is set.
//         that means that now the OS really starts using the framebuffer
//         before the aquire command OS is fetching information.
//         and before aquire the framebuffer has to tell that the screen is connected
//         otherwise it is ignored (there was no screen during information gathering, so there will never be one...)
//Power:   power our virtual hardware on or off
IOReturn info_ennowelbers_proxyframebuffer_fbuffer::setAttribute( IOSelect attribute, uintptr_t value )
{
	IOReturn ret=super::setAttribute(attribute, value);
	union myvar
	{
		IOSelect attribute;
		char param[5];
	};
	myvar var;
	var.attribute=attribute;
	var.param[4]='\0';
	if(attribute==kIOCapturedAttribute)
	{
		if(started==false)
		{
			started=true;
			connectChangeInterrupt(this,0);
		}
	}
	if(attribute==kIOPowerAttribute)
	{
		handleEvent((value>=1 ? kIOFBNotifyWillPowerOn : kIOFBNotifyWillPowerOff), (void*)TRUE);
		handleEvent((value>=1 ? kIOFBNotifyDidPowerOn : kIOFBNotifyDidPowerOff), (void*)TRUE);
		ret=kIOReturnSuccess;
	}
	IOLog("EWProxyFrameBuffer: setAttribute(%s,%x)=%x\n",var.param,(unsigned int)value,ret);
	return ret;
}

//Every framebuffer has (in theory) at least (but not limited to) one connection.
//that is... the thing where you plug in your screen.
//however, documentation tells that "good habit" is to have one framebuffer per screen.
//The *AttributeForConnection functions are used to gather information about / drive a connected screen
//We're not powering any hardware, but we still need to tell "done" upon power changes
//Concerning Probe:
//As far as i recall, whenever a framebuffer tells OS about a screen change, it calls Probe on
//all connections on all framebuffers. When the connection really changed, the framebuffer should tell
//by re-interrupting again. Actually this implementation is not correct, however
//OS understands it. It simply means that whenever a real screen is (dis)connected, our virtual one is
//reconnected. OS can handle it...
//TODO
IOReturn info_ennowelbers_proxyframebuffer_fbuffer::setAttributeForConnection(IOIndex connection, IOSelect attribute, uintptr_t value)
{
	if(attribute==kConnectionProbe)
	{
		IOLog("EWProxyFrameBuffer: Sense!\n");
		connectChangeInterrupt(this,0);
//		if(interrupts[1]!=NULL)
//		{
//			interrupts[1](interruptTargets[1],interruptRefs[1]);
//		}
		return kIOReturnSuccess;
	}
	if(attribute==kConnectionPower)
	{
		return kIOReturnSuccess;
	}
	IOReturn ret=super::setAttributeForConnection(connection,attribute, value);
	union myvar
	{
		IOSelect attribute;
		char param[5];
	};
	myvar var;
	var.attribute=attribute;
	var.param[4]='\0';
	IOLog("EWProxyFrameBuffer: setAttributeForConnection(%d,%s,%x)=%x\n",(int)connection,var.param,(unsigned int)value,(unsigned int)ret);
	return ret;

}

//There is only one interesting Attribute OS reads for each connection
//The "is there a screen connected?" attribute.
//If we're not aquired, we have to return 1.
//If we're aquired, we have to tell the truth.
//
IOReturn info_ennowelbers_proxyframebuffer_fbuffer::getAttributeForConnection(IOIndex connectIndex, IOSelect attribute, uintptr_t *value)
{
	union myvar
	{
		IOSelect attribute;
		char param[5];
	};
	myvar var;
	var.attribute=attribute;
	var.param[4]='\0';
	IOLog("EWProxyFrameBuffer: getAttributeForConnection(%d,%s).\n",(int)connectIndex,var.param);
	if(attribute==kConnectionEnable || attribute==kConnectionCheckEnable)
	{
		if(value!=NULL)
		{
			if(connected==false)
				*value=0;
			else
				*value=1;
			//if(started==false)
			//	*value=1;
		}
		return kIOReturnSuccess;
	}
//	if(attribute==kConnectionFlags)
//	{
//		if(value!=NULL)
//			*value=0;
//		return kIOReturnSuccess;
//	}
//	if(attribute==kConnectionChanged)
//	{
//		if(value!=NULL)
//			*value=0;
//		return kIOReturnSuccess;
//	}
	IOReturn ret= super::getAttributeForConnection(connectIndex, attribute, value);
	if(value!=NULL)
		IOLog("EWProxyFrameBuffer: Value= %x, Ret=%x\n",(unsigned int)*value,ret);
	else
		IOLog("EWProxyFrameBuffer: Ret=%x\n",ret);
	return ret;
}

bool info_ennowelbers_proxyframebuffer_fbuffer::init(OSDictionary *dict)
{
	bool res = super::init(dict);
	IOLog("EWProxyFrameBuffer: FBINIT\n");
	return res;
}

//OS is greedy. Once a framebuffer is in the Registry, it will not go away.
//so this function only exists to stop the compiler from warning.
void info_ennowelbers_proxyframebuffer_fbuffer::free(void)
{
	IOLog("EWProxyFrameBuffer: Free\n");
	super::free();
}

bool info_ennowelbers_proxyframebuffer_fbuffer::start(IOService *provider)
{
	bool res=super::start(provider);
	//PMinit();
	connected=0;
	graphicMem=NULL;
	started=false;
	fProvider=OSDynamicCast(info_ennowelbers_proxyframebuffer_driver,provider);
	if(res && fProvider!=NULL)
	{
		//fProvider->joinPMtree(this);
	}
	IOLog("EWProxyFrameBuffer: Starting\n");
	if(fProvider==NULL)
		return false;
	return res;
}

void info_ennowelbers_proxyframebuffer_fbuffer::stop(IOService *provider)
{
	super::stop(provider);
	if(graphicMem!=NULL)
	{
		cursorMapping->release();
		cursorMem->release();
		cursorMem=NULL;
		graphicMem->release();
		graphicMem=NULL;
	}
	IOLog("EWProxyFrameBuffer: Stopping\n");
}

//provides OS with the memory range dependend on our current resolution
IODeviceMemory * info_ennowelbers_proxyframebuffer_fbuffer::getApertureRange(IOPixelAperture aperture)
{
	IOLog("EWProxyFrameBuffer: getApertureRange\n");
	EWProxyFramebufferModeInfo info;
	fProvider->getmodeInfo(mode, &info);
	IODeviceMemory *dev=IODeviceMemory::withSubRange((IODeviceMemory*)graphicMem,0,(info.height*(info.width*4+32)+128));
//	IODeviceMemory *dev=IODeviceMemory::withRange(graphicPhysVRAM, (fProvider->height*(fProvider->width*4+32)+128));
	return dev;
}

//OS is greedy when it comes to graphic memory. It wants the whole thing.
//and... it releases it, so we're overretaining here
IODeviceMemory * info_ennowelbers_proxyframebuffer_fbuffer::getVRAMRange()
{
	IOLog("EWProxyFrameBuffer: getVRAMRange\n");
	graphicMem->retain();
	return (IODeviceMemory*)graphicMem;
}

//this one gets called when OS is ready for our hardware.
//we should to all the hardware initialization stuff in here
//as we're forced to have the graphic mem around all the time
//we're initializing by allocating worst-case-buffers
//and keep them.
//Framebuffer magic: Framebuffers only work when present during boot
//                   Framebuffers only work when having a screen before aquire()
//                   Framebuffers only work when having graphic mem
//Remember: this memory is aquired during boot and will be completely gone
//          Therefore it's preferred to set a constrained max resolution
//          and forbidden to go to higher resolutions than that.
IOReturn info_ennowelbers_proxyframebuffer_fbuffer::enableController()
{
	IOLog("EWProxyFrameBuffer: enableController\n");
	//I have no idea why we need 32 extra bytes per row and 128 bytes extra, but...
	//it only works with these extra buffers
	//Size adaption: to increase memory, I provide 1k per line and 1 meg at the end
	//this is for ansgar!
	//graphicSize=fProvider->getMaxHeight()*(fProvider->getMaxWidth()*4+32)+128;//width*height*4 buffer size, enough space for 4 buffers
	graphicSize=fProvider->getMaxHeight()*(fProvider->getMaxWidth()*4+1024)+10490880;//width*height*4 buffer size, enough space for 4 buffers
	while( graphicSize % PAGE_SIZE != 0)
	{
		graphicSize++;
	}
	mode=1;
//	graphicSize=graphicSize*4;
//	graphicMem=IODeviceMemory::withRange(graphicPhysVRAM, graphicSize);
//	apertureMem=IODeviceMemory::withRange(graphicPhysVRAM,graphicSize/4);
//	graphicMem=IOBufferMemoryDescriptor::withOptions(kIODirectionInOut|kIOMemoryKernelUserShared,graphicSize,PAGE_SIZE);
	graphicMem=IOBufferMemoryDescriptor::withCapacity(graphicSize, kIODirectionInOut);
	//i'm not sure whether we could reduce this size, at least that's a very huge cursor.
	cursorMem=IOBufferMemoryDescriptor::withCapacity((320*4+32)*320+128, kIODirectionInOut);//cursor buffer, 320x320 px cursor size maximum;
	cursorMapping=cursorMem->map(kIOMapAnywhere);
	cursorBuf=(UInt8*)cursorMapping->getVirtualAddress();
	IOLog("EWProxyFrameBuffer: controller memory: size=%d bytes\n",graphicSize);
	if(graphicMem==NULL)
	{
		IOLog("EWProxyFrameBuffer: unable to reserve memory!\n");
	}
//	IOLog("IODeviceMemory: %x\n",(int)apertureMem);
	//power management is explained (a bit) in EWProxyFrameBufferDriver
	static IOPMPowerState myPowerStates[3];
//    getProvider()->joinPMtree(this);
	myPowerStates[0].version=1;
	myPowerStates[0].capabilityFlags=0;
	myPowerStates[0].outputPowerCharacter=0;
	myPowerStates[0].inputPowerRequirement=0;
	myPowerStates[1].version=1;
	myPowerStates[1].capabilityFlags=0;
	myPowerStates[1].outputPowerCharacter=0;
	myPowerStates[1].inputPowerRequirement=IOPMPowerOn;
	myPowerStates[2].version=1;
	myPowerStates[2].capabilityFlags=IOPMDeviceUsable;
	myPowerStates[2].outputPowerCharacter=IOPMPowerOn;
	myPowerStates[2].inputPowerRequirement=IOPMPowerOn;
	registerPowerDriver(this, myPowerStates, 3);
	temporaryPowerClampOn();
	changePowerStateTo(2);
	getProvider()->setProperty(kIOPMIsPowerManagedKey, true);
	return kIOReturnSuccess;
}

//as told above, framebuffers could have more than one screen (in theory).
//but... OS doesn't support it. i think. They tell us to return 1.
IOItemCount info_ennowelbers_proxyframebuffer_fbuffer::getConnectionCount()
{
	/*if(connected==0)result=0;
	else
		result=1;*/
	IOLog("EWProxyFrameBuffer: GetConnectionCount()=1\n");
	return 1;
}

//This Function is used by OS to get current Display Mode
IOReturn info_ennowelbers_proxyframebuffer_fbuffer::getCurrentDisplayMode(IODisplayModeID * displayMode, IOIndex * depth)
{
	IOLog("EWProxyFrameBuffer: getCurrentDisplayMode\n");
	if(displayMode==NULL)
		return kIOReturnBadArgument;
	if(depth==NULL)
		return kIOReturnBadArgument;
	*displayMode=mode;
	*depth=0;
	return kIOReturnSuccess;
}

//OS wants to fill lists and needs the total amount of possible modes
IOItemCount info_ennowelbers_proxyframebuffer_fbuffer::getDisplayModeCount()
{
	IOLog("EWProxyFrameBuffer: getDisplayModeCount\n");
	return fProvider->getModeCount();
}

//OS first calls getDisplayModeCount, allocates a buffer and then calls getModes.
//so the pointer is garantueed to be big enough for the number of modes given before.
//the funny thing: a display mode is ... an integer.
//all the other information are transported using getInformationForDisplayMode
IOReturn info_ennowelbers_proxyframebuffer_fbuffer::getDisplayModes(IODisplayModeID * allDisplayModes)
{
	IOLog("EWProxyFrameBuffer: getDisplayModes\n");
	for(int i=1;i<=fProvider->getModeCount();i++)
	{
		allDisplayModes[i-1]=i;
	}
	return kIOReturnSuccess;
}

//returns details about a given display mode (width, height, refresh rate, flags, amount of possible depths)
//i have no knowledge about those flags. that way they work.
//an extension would be (to prevent OS from switching) to make them visible based on the current mode setting
IOReturn info_ennowelbers_proxyframebuffer_fbuffer::getInformationForDisplayMode(IODisplayModeID displayMode, IODisplayModeInformation *info)
{
	IOLog("EWProxyFrameBuffer: getInformationForDisplayMode\n");
	EWProxyFramebufferModeInfo pinfo;
	IOReturn ret=fProvider->getmodeInfo(displayMode, &pinfo);
	if(ret!=kIOReturnSuccess)
		return ret;
	bzero(info,sizeof(*info));
	info->nominalWidth=pinfo.width;
	info->nominalHeight=pinfo.height;
	info->maxDepthIndex=0;
	info->refreshRate=60<<16;
	info->flags=kDisplayModeAlwaysShowFlag|kDisplayModeValidFlag|kDisplayModeDefaultFlag;
	return kIOReturnSuccess;
}

//In theory the graphic mem could be in different formats.
//I have no idea about their physical layout in memory.
//The details about this pixel format are ... in our domain.
//After asking us for a name OS asks for details with getPixelInformation.
const char * info_ennowelbers_proxyframebuffer_fbuffer::getPixelFormats()
{
	IOLog("EWProxyFrameBuffer: getPixelFormats\n");
	static const char * fmts=IO32BitDirectPixels "\0\0";
	return fmts;
}

//this function is deprecated from what i recall
UInt64 info_ennowelbers_proxyframebuffer_fbuffer::getPixelFormatsForDisplayMode(IODisplayModeID displayMode, IOIndex depth)
{
	IOLog("EWProxyFrameBuffer: getPixelFormatsForDisplayMode\n");
	return 0;
}

//This function tells OS where in these 32 bits are red, green and blue, how many bits each component we use and how
//many components we really use.
//we could save some space by using a smaller pixel layout, but we need to convert it into a CGImage in user space,
//this is the simplest copy routine.
IOReturn info_ennowelbers_proxyframebuffer_fbuffer::getPixelInformation(IODisplayModeID displayMode, IOIndex depth, IOPixelAperture aperture, IOPixelInformation * pixelInfo)
{
	IOLog("EWProxyFrameBuffer: getPixelInformation(mode=%x, depth=%x, aperture=%x)\n",(int)displayMode,(int)depth,(int)aperture);
	if(depth!=0)
	{
		IOLog("EWProxyFrameBuffer: Unsupported!\n");
		return kIOReturnUnsupportedMode;
	}
	else
	{
		EWProxyFramebufferModeInfo pinfo;
		IOReturn ret=fProvider->getmodeInfo(displayMode, &pinfo);
		if(ret!=kIOReturnSuccess)
			return ret;
		bzero(pixelInfo,sizeof(*pixelInfo));
		IOLog("EWProxyFrameBuffer: returning for %d x %d\n",pinfo.width,pinfo.height);
		pixelInfo->bytesPerRow=pinfo.width*4+32;//32 byte row header??
		pixelInfo->bitsPerPixel=32;
		pixelInfo->pixelType=kIORGBDirectPixels;
		pixelInfo->componentCount=3;
		pixelInfo->bitsPerComponent=8;
		strlcpy(pixelInfo->pixelFormat, IO32BitDirectPixels, sizeof(pixelInfo->pixelFormat));
		pixelInfo->activeWidth=pinfo.width;
		pixelInfo->activeHeight=pinfo.height;
		pixelInfo->componentMasks[0]=0x00FF0000;
		pixelInfo->componentMasks[1]=0x0000FF00;
		pixelInfo->componentMasks[2]=0x000000FF;
		IOLog("EWProxyFrameBuffer: Pixel Data: bytesPerRow=%d bytesPerPlane=%d bitsPerPixel=%d pixelType=%d components=%d bitsPerComponent=%d pixelformat=%s width=%d height=%d masks(%x,%x,%x)\n",
			  (int)pixelInfo->bytesPerRow,(int)pixelInfo->bytesPerPlane,(int)pixelInfo->bitsPerPixel,(int)pixelInfo->pixelType,(int)pixelInfo->componentCount, (int)pixelInfo->bitsPerComponent,pixelInfo->pixelFormat,
			  (int)pixelInfo->activeWidth,(int)pixelInfo->activeHeight,(unsigned int)pixelInfo->componentMasks[0],(unsigned int)pixelInfo->componentMasks[1],(unsigned int)pixelInfo->componentMasks[2]);
	}
	return kIOReturnSuccess;
}

//OS uses this function to switch mode
//currently we always return unsupported but we still tell OS that resolution changed
//would be better to only show the mode currently configured.
IOReturn info_ennowelbers_proxyframebuffer_fbuffer::setDisplayMode(IODisplayModeID displayMode, IOIndex depth)
{
	IOLog("EWProxyFrameBuffer: setDisplayMode(%x,%d)\n",(unsigned int)displayMode,(int)depth);
	if(displayMode<1 || displayMode>fProvider->getModeCount() || depth!=0)
	{
		IOLog("EWProxyFrameBuffer: unsupported mode!\n");
		return kIOReturnUnsupportedMode;
	}
	if(mode!=displayMode)
	{
		return kIOReturnUnsupportedMode;
	}
	mode=displayMode;
	handleEvent(kIOFBNotifyDisplayModeWillChange, NULL);
	handleEvent(kIOFBNotifyDisplayModeDidChange, NULL);
	return kIOReturnSuccess;
}

//OS uses this function to provide us with a new cursor image
IOReturn info_ennowelbers_proxyframebuffer_fbuffer::setCursorImage(void *img)
{
	IOHardwareCursorDescriptor cdesc;
	IOHardwareCursorInfo cinfo;

	cdesc.majorVersion=kHardwareCursorDescriptorMajorVersion;
	cdesc.minorVersion=kHardwareCursorDescriptorMinorVersion;
	cdesc.height=320;
	cdesc.width=320;
	cdesc.bitDepth=kIO32ARGBPixelFormat;
	cdesc.maskBitDepth=0;
	cdesc.numColors=0;
	cdesc.colorEncodings=NULL;
	cdesc.flags=0;
	cdesc.supportedSpecialEncodings=0;
	memset(cdesc.specialEncodings, 0, sizeof(cdesc.specialEncodings));

	cinfo.majorVersion=kHardwareCursorInfoMajorVersion;
	cinfo.minorVersion=kHardwareCursorInfoMinorVersion;
	cinfo.colorMap=NULL;
	memset(cinfo.reserved, 0, sizeof(cinfo.reserved));
	cinfo.hardwareCursorData=cursorBuf;
	//the cool thing: as we only get a pointer we have no idea about it's format.
	//therefore we define the format we want (see structures above)
	//and tell OS (parent class, essentially) to convert it.
	//img is our own buffer. We don't even need to copy it into our buffer afterwards.
	bool ret=convertCursorImage(img, &cdesc, &cinfo);
	IOLog("EWProxyFrameBuffer: convertCursorImage()=%s\n",(ret?"true":"false"));
	if(ret)
	{
		IOLog("EWProxyFrameBuffer: cursor size: %d x %d\n",(int)cinfo.cursorWidth,(int)cinfo.cursorHeight);
		cursorWidth=cinfo.cursorWidth;
		cursorHeight=cinfo.cursorHeight;
		//our user space app can register a few events
		//one of those is "cursor changed"
		//here we're firing this event.
		if(fProvider->eventClient!=NULL)
		{
			fProvider->eventClient->FireCursorImageChanged();
		}
		return kIOReturnSuccess;
	}
	//for step one we always return unsupported. we just want to get the cursor image
	return kIOReturnUnsupported;
}

//using this function OS tells us where the cursor is and whether it's visible or not.
//don't get me wrong, a framebuffer can work without a hardware cursor.
//OS then draws the cursor directly into graphic mem. Not very effective, though.
IOReturn info_ennowelbers_proxyframebuffer_fbuffer::setCursorState(SInt32 x, SInt32 y, bool visible)
{
	cursorX=x;
	cursorY=y;
	cursorVisible=visible;
	if(fProvider->eventClient!=NULL)
	{
		fProvider->eventClient->FireCursorStateChanged();
	}
	return kIOReturnSuccess;
}


text:
import { AppState } from "../";
import { WorldGeneratorObject } from "../services";
import { SkillKeys } from "../constants";

export const appRestart = () => ({ type: "CHARACTER_RESTART" });
export const appSave = () => ({ type: "CHARACTER_SAVE" });

export const updateCharacterName = (name: string) => ({
  type: "UPDATE_NAME",
  name,
});
export const updateCharacterStats = (statsArray: number[]) => ({
  type: "UPDATE_STATS",
  statsArray,
});
export const setAvailableSkillCount = (availableSkillCount: number) => ({
  type: "SET_AVAILABLE_SKILL_COUNT",
  availableSkillCount,
});
export const updateHomeworld = (homeWorld: WorldGeneratorObject) => ({
  type: "UPDATE_HOMEWORLD",
  homeWorld,
});
export const incrementSkill = (skillKey: SkillKeys) => ({
  type: "INCREMENT_SKILL",
  skillKey,
});
export const decrementSkill = (skillKey: SkillKeys) => ({
  type: "DECREMENT_SKILL",
  skillKey,
});

export const updateForm = (
  formName: AppState.FormNames,
  fieldName: string,
  fieldValue: string | number
) => {
  return {
    type: "UPDATE_FORM",
    formName,
    fieldName,
    fieldValue,
  };
};

export const goToStep = (step: string) => {
  return {
    type: "GO_TO_STEP",
    step,
  };
};

redpajama_set_name: RedPajamaGithub


text:
var mongoose = require("mongoose");

var url = process.env.MONGOLAB_URI || "mongodb://localhost/whatsup";

mongoose.connect(url, function () {
    console.log("mongodb connected");
});

module.exports = mongoose;


text:
package org.gradle.api.artifacts;

import groovy.lang.Closure;
import org.gradle.api.Action;
import org.gradle.internal.HasInternalProtocol;

/***
 * Represents a container for component selection rules.  Rules can be applied as part of the
 * resolutionStrategy of a configuration and individual components can be explicitly accepted
 * or rejected by rule.  Components that are neither accepted or rejected will be subject to
 * the default version matching strategies.
 *
 *

 *     configurations {
 *         conf {
 *             resolutionStrategy {
 *                 componentSelection {
 *                     all { ComponentSelection selection ->
 *                         if (selection.candidate.module == 'someModule' && selection.candidate.version == '1.1') {
 *                             selection.reject("bad version '1.1' for 'someModule'")
 *                         }
 *                     }
 *                     all { ComponentSelection selection ->
 *                         if (selection.candidate.module == 'someModule' && selection.getDescriptor(IvyModuleDescriptor)?.branch == 'testing') {
 *                             if (selection.metadata == null || selection.metadata.status != 'milestone') {
 *                                 selection.reject("only use milestones for someModule:testing")
 *                             }
 *                         }
 *                     }
 *                     withModule("org.sample:api") { ComponentSelection selection ->
 *                         if (selection.candidate.version == "1.1") {
 *                             selection.reject("known bad version")
 *                         }
 *                     }
 *                 }
 *             }
 *         }
 *     }
 *

 */
@HasInternalProtocol
public interface ComponentSelectionRules {
    /**
     * Adds a simple component selection rule that will apply to all resolved components.
     * Each rule will receive a {@link ComponentSelection} object as an argument.
     *
     * @param selectionAction the Action that implements a rule to be applied
     * @return this
     */
    ComponentSelectionRules all(Action<? super ComponentSelection> selectionAction);

    /**
     * Adds a component selection rule that will apply to all resolved components.
     *
     * Each rule will receive a {@link ComponentSelection} object as an argument.
     *
     * @param closure the Closure that implements a rule to be applied
     * @return this
     */
    ComponentSelectionRules all(Closure<?> closure);

    /**
     * Adds a rule-source backed component selection rule that will apply to all resolved components.
     *
     * The ruleSource provides the rule as exactly one rule method annotated with {@link org.gradle.model.Mutate}.
     *
     * This rule method:
     *

     *
must return void.

     *
must have {@link org.gradle.api.artifacts.ComponentSelection} as its parameter.

     *

     *
     * @param ruleSource an instance providing a rule implementation
     * @return this
     */
    ComponentSelectionRules all(Object ruleSource);

    /**
     * Adds a component selection rule that will apply to the specified module.
     * Each rule will receive a {@link ComponentSelection} object as an argument.
     *
     * @param id the module to apply this rule to in "group:module" format or as a {@link org.gradle.api.artifacts.ModuleIdentifier}
     * @param selectionAction the Action that implements a rule to be applied
     * @return this
     */
    ComponentSelectionRules withModule(Object id, Action<? super ComponentSelection> selectionAction);

    /**
     * Adds a component selection rule that will apply to the specified module.
     *
     * Each rule will receive a {@link ComponentSelection} object as an argument.
     *
     * @param id the module to apply this rule to in "group:module" format or as a {@link org.gradle.api.artifacts.ModuleIdentifier}
     * @param closure the Closure that implements a rule to be applied
     * @return this
     */
    ComponentSelectionRules withModule(Object id, Closure<?> closure);

    /**
     * Adds a rule-source backed component selection rule that will apply to the specified module.
     *
     * The ruleSource provides the rule as exactly one rule method annotated with {@link org.gradle.model.Mutate}.
     *
     * This rule method:
     *

     *
must return void.

     *
must have {@link org.gradle.api.artifacts.ComponentSelection} as its parameter.

     *

     *
     * @param id the module to apply this rule to in "group:module" format or as a {@link org.gradle.api.artifacts.ModuleIdentifier}
     * @param ruleSource an instance providing a rule implementation
     * @return this
     */
    ComponentSelectionRules withModule(Object id, Object ruleSource);
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Ukr. bot. Zh. 45(5): 62 (1988)

#### Original name
Erysiphe adenophorae R.Y. Zheng & G.Q. Chen

### Remarks
null


text:
package com.example.androidcomm;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

/**
 * Receive data from Case5F2Fragment.
 */
public class Case5F1Fragment extends Fragment{

    private static String ARG_NAME = "Name";

    Button mNext;

    TextView mName;
    private String mNameString;

    public static Case5F1Fragment newInstance(String name){
        Bundle args = new Bundle();
        args.putSerializable(ARG_NAME, name);
        Case5F1Fragment fragment = new Case5F1Fragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null)
            mNameString = getArguments().getString(ARG_NAME);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_case5_f1, container, false);

        mName = (TextView) v.findViewById(R.id.tv_name);
        validateName();

        mNext = (Button) v.findViewById(R.id.bt_next);
        mNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Case5F2Fragment f2 = new Case5F2Fragment();
                getFragmentManager()
                        .beginTransaction()
                        .replace(((ViewGroup)getView().getParent()).getId(), f2)
                        .addToBackStack(null)
                        .commit();
            }
        });

        return v;
    }

    private void validateName() {
        if ("".equals(mNameString)) {
            mName.setText(getString(R.string.no_name_provided));
            mName.setTextColor(Color.RED);
            mName.setTypeface(null, Typeface.ITALIC);
        } else {
            mName.setText(mNameString);
            mName.setTextColor(Color.BLUE);
            mName.setTypeface(null, Typeface.BOLD);
        }
    }

}


text:
var util = require('util');
var BaseGateway = require('42-cent-base').BaseGateway;
var paypal = require('paypal-rest-sdk');
var assert = require('assert');
var mapKeys = require('42-cent-util').mapKeys;
var P = require('bluebird');
var assign = require('object-assign');
var cardType = require('credit-card-type');
var creditCardSchema = {
  creditCardNumber: 'number',
  expirationMonth: 'expire_month',
  expirationYear: 'expire_year',
  cvv2: 'cvv2',
  billingFirstName: 'first_name',
  billingLastName: 'last_name'
};
var GatewayError = require('42-cent-base').GatewayError;

var billingAddressSchema = {
  billingPhone: 'phone',
  billingAddress1: 'line1',
  billingAddress2: 'line2',
  billingCity: 'city',
  billingState: 'state',
  billingPostalCode: 'postal_code',
  billingCountry: 'country_code'
};

function Paypal (options) {
  assert(options.CLIENT_ID, 'you must provide CLIENT_ID in the options');
  assert(options.CLIENT_SECRET, 'you must provide CLIENT_SECRET in the options');
  BaseGateway.call(this, options);
  this.paypal = paypal;
  this.paypal.configure({
    mode: options.testMode === true ? 'sandbox' : 'live',
    client_id: options.CLIENT_ID,
    client_secret: options.CLIENT_SECRET
  });

}
util.inherits(Paypal, BaseGateway);

function handleError (err) {
  if (err.httpStatusCode && err.httpStatusCode >= 400) {
    throw  new GatewayError(err.message, err);
  } else {
    throw err;
  }
}

function createPayment (intent) {
  return function submitTransaction (order, creditcard, prospect, other) {
    return P.resolve()
      .then(function () {
        var type;
        var pay = P.promisify(this.paypal.payment.create.bind(this.paypal.payment));
        var cc = mapKeys(assign({}, creditcard, prospect), creditCardSchema);
        var amount = parseNumber(order.amount);
        cc.billing_address = mapKeys(prospect, billingAddressSchema, {});
        type = cardType(creditcard.creditCardNumber)[0].niceType.toLowerCase();
        type = type === 'american express' ? 'amex' : type;
        cc.type = type;
        var payload = {
          intent: intent,
          payer: {
            payment_method: 'credit_card',
            funding_instruments: [
              {credit_card: cc}
            ]
          },
          transactions: [{
            amount: {
              total: amount,
              currency: order.currency || 'USD'
            }
          }]
        };
        return pay(payload);
      }.bind(this))
      .then(function parse (response) {
        var relatedResource = response.transactions[0].related_resources[0];
        var id = intent === 'sale' ? relatedResource.sale.id : relatedResource.authorization.id;
        return {
          _original: response,
          transactionId: id
        };
      })
      .catch(handleError);
  }
}

function parseNumber (number) {
  return typeof number === 'number' ? number.toFixed(2) : parseFloat(number.toString()).toFixed(2);
}

Paypal.prototype.submitTransaction = createPayment('sale');

Paypal.prototype.authorizeTransaction = createPayment('authorize');

Paypal.prototype.refundTransaction = function refundTransaction (transactionId, options) {

  return P.resolve()
    .then(function () {
      options = options || {};
      var amount = {};
      var payload = {};
      var refund = P.promisify(this.paypal.sale.refund.bind(this.paypal.sale));
      if (options.amount) {
        amount.total = parseNumber(options.amount);
      }
      if (options.currency) {
        amount.currency = options.currency;
      }
      payload = amount.total ? {amount: amount} : payload;
      return refund(transactionId, payload)
    }.bind(this))
    .then(function (result) {
      return {
        _original: result
      };
    })
    .catch(handleError);

};

Paypal.prototype.voidTransaction = function voidTransaction (authorizationId, options) {
  return P.resolve()
    .then(function () {
      var paypalVoid = P.promisify(this.paypal.authorization.void.bind(this.paypal.authorization));
      return paypalVoid(authorizationId)
    }.bind(this))
    .then(function (res) {
      return {
        _original: res
      };
    })
    .catch(handleError);
};

Paypal.prototype.createCustomerProfile = function createCustomerProfile (creditcard, prospect, options) {
  return P.resolve()
    .then(function () {
      options = options || {};
      var createProfile = P.promisify(this.paypal.creditCard.create.bind(this.paypal.creditCard));
      var cc = mapKeys(assign({}, creditcard, prospect), creditCardSchema);
      var type = cardType(creditcard.creditCardNumber)[0].niceType.toLocaleLowerCase();
      type = type === 'american express' ? 'amex' : type;
      cc.billing_address = mapKeys(prospect, billingAddressSchema, {});
      cc.type = type;
      cc = assign(cc, options);
      return createProfile(cc);
    }.bind(this))
    .then(function (result) {
      return {
        profileId: result.id,
        _original: result
      };
    })
    .catch(handleError);
};

Paypal.prototype.chargeCustomer = function chargeCustomer (order, prospect) {
  return P.resolve()
    .then(function () {
      assert(prospect.profileId, 'prospect must have a profileId');
      var pay = P.promisify(this.paypal.payment.create.bind(this.paypal.payment));
      var amount = parseNumber(order.amount);
      var payload = {
        intent: 'sale',
        payer: {
          payment_method: 'credit_card',
          funding_instruments: [
            {
              credit_card_token: {
                credit_card_id: prospect.profileId
              }
            }
          ]
        },
        transactions: [{
          amount: {
            total: amount,
            currency: order.currency || 'USD'
          }
        }]
      };
      return pay(payload);
    }.bind(this))
    .then(function (response) {
      var relatedResource = response.transactions[0].related_resources[0];
      var id = relatedResource.sale.id;
      return {
        _original: response,
        transactionId: id
      };
    })
    .catch(handleError)
};

module.exports = Paypal;


text:
namespace offline_items_collection {

struct OfflineItemVisuals;

namespace android {

// A helper class for creating Java OfflineItemVisuals instances from the C++
// OfflineItemVisuals counterpart.
class OfflineItemVisualsBridge {
 public:
  // Creates a Java OfflineItemVisuals from |visuals|.
  static base::android::ScopedJavaLocalRef<jobject> CreateOfflineItemVisuals(
      JNIEnv* env,
      std::unique_ptr<OfflineItemVisuals> visuals);

 private:
  OfflineItemVisualsBridge();
};

}  // namespace android
}  // namespace offline_items_collection

#endif  // COMPONENTS_OFFLINE_ITEMS_COLLECTION_CORE_ANDROID_OFFLINE_ITEM_VISUALS_BRIDGE_H_


text:
//! \file modes.h
//! \brief Class file for modes of operation.

#ifndef CRYPTOPP_MODES_H
#define CRYPTOPP_MODES_H

#include "cryptlib.h"
#include "secblock.h"
#include "misc.h"
#include "strciphr.h"
#include "argnames.h"
#include "algparam.h"

// Issue 340
#if CRYPTOPP_GCC_DIAGNOSTIC_AVAILABLE
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wconversion"
# pragma GCC diagnostic ignored "-Wsign-conversion"
#endif

#if CRYPTOPP_MSC_VERSION
# pragma warning(push)
# pragma warning(disable: 4231 4275)
# if (CRYPTOPP_MSC_VERSION >= 1400)
#  pragma warning(disable: 6011 6386 28193)
# endif
#endif

NAMESPACE_BEGIN(CryptoPP)

//! \class CipherModeDocumentation
//! \brief Block cipher mode of operation information
//! \details Each class derived from this one defines two types, Encryption and Decryption,
//!   both of which implement the SymmetricCipher interface.
//!   For each mode there are two classes, one of which is a template class,
//!   and the other one has a name that ends in "_ExternalCipher".
//!   The "external cipher" mode objects hold a reference to the underlying block cipher,
//!   instead of holding an instance of it. The reference must be passed in to the constructor.
//!   For the "cipher holder" classes, the CIPHER template parameter should be a class
//!   derived from BlockCipherDocumentation, for example DES or AES.
//! \details See NIST SP 800-38A for definitions of these modes. See
//!   AuthenticatedSymmetricCipherDocumentation for authenticated encryption modes.
struct CipherModeDocumentation : public SymmetricCipherDocumentation
{
};

//! \class CipherModeBase
//! \brief Block cipher mode of operation information
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CipherModeBase : public SymmetricCipher
{
public:
	virtual ~CipherModeBase() {}
	size_t MinKeyLength() const {return m_cipher->MinKeyLength();}
	size_t MaxKeyLength() const {return m_cipher->MaxKeyLength();}
	size_t DefaultKeyLength() const {return m_cipher->DefaultKeyLength();}
	size_t GetValidKeyLength(size_t n) const {return m_cipher->GetValidKeyLength(n);}
	bool IsValidKeyLength(size_t n) const {return m_cipher->IsValidKeyLength(n);}

	unsigned int OptimalDataAlignment() const {return m_cipher->OptimalDataAlignment();}

	unsigned int IVSize() const {return BlockSize();}
	virtual IV_Requirement IVRequirement() const =0;

	void SetCipher(BlockCipher &cipher)
	{
		this->ThrowIfResynchronizable();
		this->m_cipher = &cipher;
		this->ResizeBuffers();
	}

	void SetCipherWithIV(BlockCipher &cipher, const byte *iv, int feedbackSize = 0)
	{
		this->ThrowIfInvalidIV(iv);
		this->m_cipher = &cipher;
		this->ResizeBuffers();
		this->SetFeedbackSize(feedbackSize);
		if (this->IsResynchronizable())
			this->Resynchronize(iv);
	}

protected:
	CipherModeBase() : m_cipher(NULLPTR) {}
	inline unsigned int BlockSize() const {CRYPTOPP_ASSERT(m_register.size() > 0); return (unsigned int)m_register.size();}
	virtual void SetFeedbackSize(unsigned int feedbackSize)
	{
		if (!(feedbackSize == 0 || feedbackSize == BlockSize()))
			throw InvalidArgument("CipherModeBase: feedback size cannot be specified for this cipher mode");
	}

	virtual void ResizeBuffers();

	BlockCipher *m_cipher;
	AlignedSecByteBlock m_register;
};

//! \class ModePolicyCommonTemplate
//! \brief Block cipher mode of operation common operations
//! \tparam POLICY_INTERFACE common operations
template <class POLICY_INTERFACE>
class CRYPTOPP_NO_VTABLE ModePolicyCommonTemplate : public CipherModeBase, public POLICY_INTERFACE
{
	unsigned int GetAlignment() const {return m_cipher->OptimalDataAlignment();}
	void CipherSetKey(const NameValuePairs &params, const byte *key, size_t length);
};

template <class POLICY_INTERFACE>
void ModePolicyCommonTemplate<POLICY_INTERFACE>::CipherSetKey(const NameValuePairs &params, const byte *key, size_t length)
{
	m_cipher->SetKey(key, length, params);
	ResizeBuffers();
	int feedbackSize = params.GetIntValueWithDefault(Name::FeedbackSize(), 0);
	SetFeedbackSize(feedbackSize);
}

//! \class CFB_ModePolicy
//! \brief CFB block cipher mode of operation
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CFB_ModePolicy : public ModePolicyCommonTemplate<CFB_CipherAbstractPolicy>
{
public:
	CRYPTOPP_STATIC_CONSTEXPR const char* CRYPTOPP_API StaticAlgorithmName() {return "CFB";}

	virtual ~CFB_ModePolicy() {}
	IV_Requirement IVRequirement() const {return RANDOM_IV;}

protected:
	unsigned int GetBytesPerIteration() const {return m_feedbackSize;}
	byte * GetRegisterBegin() {return m_register + BlockSize() - m_feedbackSize;}
	bool CanIterate() const {return m_feedbackSize == BlockSize();}
	void Iterate(byte *output, const byte *input, CipherDir dir, size_t iterationCount);
	void TransformRegister();
	void CipherResynchronize(const byte *iv, size_t length);
	void SetFeedbackSize(unsigned int feedbackSize);
	void ResizeBuffers();

	SecByteBlock m_temp;
	unsigned int m_feedbackSize;
};

inline void CopyOrZero(void *dest, size_t d, const void *src, size_t s)
{
	CRYPTOPP_ASSERT(dest);
	CRYPTOPP_ASSERT(d >= s);

	if (src)
		memcpy_s(dest, d, src, s);
	else
		memset(dest, 0, d);
}

//! \class OFB_ModePolicy
//! \brief OFB block cipher mode of operation
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE OFB_ModePolicy : public ModePolicyCommonTemplate<AdditiveCipherAbstractPolicy>
{
public:
	CRYPTOPP_STATIC_CONSTEXPR const char* CRYPTOPP_API StaticAlgorithmName() {return "OFB";}

	bool CipherIsRandomAccess() const {return false;}
	IV_Requirement IVRequirement() const {return UNIQUE_IV;}

private:
	unsigned int GetBytesPerIteration() const {return BlockSize();}
	unsigned int GetIterationsToBuffer() const {return m_cipher->OptimalNumberOfParallelBlocks();}
	void WriteKeystream(byte *keystreamBuffer, size_t iterationCount);
	void CipherResynchronize(byte *keystreamBuffer, const byte *iv, size_t length);
};

//! \class CTR_ModePolicy
//! \brief CTR block cipher mode of operation
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CTR_ModePolicy : public ModePolicyCommonTemplate<AdditiveCipherAbstractPolicy>
{
public:
	CRYPTOPP_STATIC_CONSTEXPR const char* CRYPTOPP_API StaticAlgorithmName() {return "CTR";}

	virtual ~CTR_ModePolicy() {}
	bool CipherIsRandomAccess() const {return true;}
	IV_Requirement IVRequirement() const {return RANDOM_IV;}

protected:
	virtual void IncrementCounterBy256();
	unsigned int GetAlignment() const {return m_cipher->OptimalDataAlignment();}
	unsigned int GetBytesPerIteration() const {return BlockSize();}
	unsigned int GetIterationsToBuffer() const {return m_cipher->OptimalNumberOfParallelBlocks();}
	void WriteKeystream(byte *buffer, size_t iterationCount)
		{OperateKeystream(WRITE_KEYSTREAM, buffer, NULLPTR, iterationCount);}
	bool CanOperateKeystream() const {return true;}
	void OperateKeystream(KeystreamOperation operation, byte *output, const byte *input, size_t iterationCount);
	void CipherResynchronize(byte *keystreamBuffer, const byte *iv, size_t length);
	void SeekToIteration(lword iterationCount);

	AlignedSecByteBlock m_counterArray;
};

//! \class BlockOrientedCipherModeBase
//! \brief Block cipher mode of operation default implementation
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE BlockOrientedCipherModeBase : public CipherModeBase
{
public:
	virtual ~BlockOrientedCipherModeBase() {}
	void UncheckedSetKey(const byte *key, unsigned int length, const NameValuePairs &params);
	unsigned int MandatoryBlockSize() const {return BlockSize();}
	bool IsRandomAccess() const {return false;}
	bool IsSelfInverting() const {return false;}
	bool IsForwardTransformation() const {return m_cipher->IsForwardTransformation();}
	void Resynchronize(const byte *iv, int length=-1) {memcpy_s(m_register, m_register.size(), iv, ThrowIfInvalidIVLength(length));}

protected:
	bool RequireAlignedInput() const {return true;}
	virtual void ResizeBuffers();

	SecByteBlock m_buffer;
};

//! \class ECB_OneWay
//! \brief ECB block cipher mode of operation default implementation
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE ECB_OneWay : public BlockOrientedCipherModeBase
{
public:
	CRYPTOPP_STATIC_CONSTEXPR const char* CRYPTOPP_API StaticAlgorithmName() {return "ECB";}

	void SetKey(const byte *key, size_t length, const NameValuePairs &params = g_nullNameValuePairs)
		{m_cipher->SetKey(key, length, params); BlockOrientedCipherModeBase::ResizeBuffers();}
	IV_Requirement IVRequirement() const {return NOT_RESYNCHRONIZABLE;}
	unsigned int OptimalBlockSize() const {return BlockSize() * m_cipher->OptimalNumberOfParallelBlocks();}
	void ProcessData(byte *outString, const byte *inString, size_t length);
};

//! \class CBC_ModeBase
//! \brief CBC block cipher mode of operation default implementation
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CBC_ModeBase : public BlockOrientedCipherModeBase
{
public:
	CRYPTOPP_STATIC_CONSTEXPR const char* CRYPTOPP_API StaticAlgorithmName() {return "CBC";}

	IV_Requirement IVRequirement() const {return UNPREDICTABLE_RANDOM_IV;}
	bool RequireAlignedInput() const {return false;}
	unsigned int MinLastBlockSize() const {return 0;}
};

//! \class CBC_Encryption
//! \brief CBC block cipher mode of operation encryption operation
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CBC_Encryption : public CBC_ModeBase
{
public:
	void ProcessData(byte *outString, const byte *inString, size_t length);
};

//! \class CBC_CTS_Encryption
//! \brief CBC-CTS block cipher mode of operation encryption operation
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CBC_CTS_Encryption : public CBC_Encryption
{
public:
	CRYPTOPP_STATIC_CONSTEXPR const char* CRYPTOPP_API StaticAlgorithmName() {return "CBC/CTS";}

	void SetStolenIV(byte *iv) {m_stolenIV = iv;}
	unsigned int MinLastBlockSize() const {return BlockSize()+1;}
	void ProcessLastBlock(byte *outString, const byte *inString, size_t length);

protected:
	void UncheckedSetKey(const byte *key, unsigned int length, const NameValuePairs &params)
	{
		CBC_Encryption::UncheckedSetKey(key, length, params);
		m_stolenIV = params.GetValueWithDefault(Name::StolenIV(), (byte *)NULLPTR);
	}

	byte *m_stolenIV;
};

//! \class CBC_Decryption
//! \brief CBC block cipher mode of operation decryption operation
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CBC_Decryption : public CBC_ModeBase
{
public:
	virtual ~CBC_Decryption() {}
	void ProcessData(byte *outString, const byte *inString, size_t length);

protected:
	virtual void ResizeBuffers();

	AlignedSecByteBlock m_temp;
};

//! \class CBC_CTS_Decryption
//! \brief CBC-CTS block cipher mode of operation decryption operation
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CBC_CTS_Decryption : public CBC_Decryption
{
public:
	unsigned int MinLastBlockSize() const {return BlockSize()+1;}
	void ProcessLastBlock(byte *outString, const byte *inString, size_t length);
};

//! \class CipherModeFinalTemplate_CipherHolder
//! \brief Block cipher mode of operation aggregate
template <class CIPHER, class BASE>
class CipherModeFinalTemplate_CipherHolder : protected ObjectHolder<CIPHER>, public AlgorithmImpl<BASE, CipherModeFinalTemplate_CipherHolder<CIPHER, BASE> >
{
public:
	static std::string CRYPTOPP_API StaticAlgorithmName()
		{return CIPHER::StaticAlgorithmName() + "/" + BASE::StaticAlgorithmName();}

	CipherModeFinalTemplate_CipherHolder()
	{
		this->m_cipher = &this->m_object;
		this->ResizeBuffers();
	}
	CipherModeFinalTemplate_CipherHolder(const byte *key, size_t length)
	{
		this->m_cipher = &this->m_object;
		this->SetKey(key, length);
	}
	CipherModeFinalTemplate_CipherHolder(const byte *key, size_t length, const byte *iv)
	{
		this->m_cipher = &this->m_object;
		this->SetKey(key, length, MakeParameters(Name::IV(), ConstByteArrayParameter(iv, this->m_cipher->BlockSize())));
	}
	CipherModeFinalTemplate_CipherHolder(const byte *key, size_t length, const byte *iv, int feedbackSize)
	{
		this->m_cipher = &this->m_object;
		this->SetKey(key, length, MakeParameters(Name::IV(), ConstByteArrayParameter(iv, this->m_cipher->BlockSize()))(Name::FeedbackSize(), feedbackSize));
	}
};

//! \class CipherModeFinalTemplate_ExternalCipher
//! \tparam BASE CipherModeFinalTemplate_CipherHolder base class
//! \details
template <class BASE>
class CipherModeFinalTemplate_ExternalCipher : public BASE
{
public:
	CipherModeFinalTemplate_ExternalCipher() {}
	CipherModeFinalTemplate_ExternalCipher(BlockCipher &cipher)
		{this->SetCipher(cipher);}
	CipherModeFinalTemplate_ExternalCipher(BlockCipher &cipher, const byte *iv, int feedbackSize = 0)
		{this->SetCipherWithIV(cipher, iv, feedbackSize);}

	std::string AlgorithmName() const
		{return (this->m_cipher ? this->m_cipher->AlgorithmName() + "/" : std::string("")) + BASE::StaticAlgorithmName();}
};

CRYPTOPP_DLL_TEMPLATE_CLASS CFB_CipherTemplate<AbstractPolicyHolder<CFB_CipherAbstractPolicy, CFB_ModePolicy> >;
CRYPTOPP_DLL_TEMPLATE_CLASS CFB_EncryptionTemplate<AbstractPolicyHolder<CFB_CipherAbstractPolicy, CFB_ModePolicy> >;
CRYPTOPP_DLL_TEMPLATE_CLASS CFB_DecryptionTemplate<AbstractPolicyHolder<CFB_CipherAbstractPolicy, CFB_ModePolicy> >;

//! \class CFB_Mode
//! \brief CFB block cipher mode of operation.
template <class CIPHER>
struct CFB_Mode : public CipherModeDocumentation
{
	typedef CipherModeFinalTemplate_CipherHolder<typename CIPHER::Encryption, ConcretePolicyHolder<Empty, CFB_EncryptionTemplate<AbstractPolicyHolder<CFB_CipherAbstractPolicy, CFB_ModePolicy> > > > Encryption;
	typedef CipherModeFinalTemplate_CipherHolder<typename CIPHER::Encryption, ConcretePolicyHolder<Empty, CFB_DecryptionTemplate<AbstractPolicyHolder<CFB_CipherAbstractPolicy, CFB_ModePolicy> > > > Decryption;
};

//! \class CFB_Mode_ExternalCipher
//! \brief CFB mode, external cipher.
struct CFB_Mode_ExternalCipher : public CipherModeDocumentation
{
	typedef CipherModeFinalTemplate_ExternalCipher<ConcretePolicyHolder<Empty, CFB_EncryptionTemplate<AbstractPolicyHolder<CFB_CipherAbstractPolicy, CFB_ModePolicy> > > > Encryption;
	typedef CipherModeFinalTemplate_ExternalCipher<ConcretePolicyHolder<Empty, CFB_DecryptionTemplate<AbstractPolicyHolder<CFB_CipherAbstractPolicy, CFB_ModePolicy> > > > Decryption;
};

//! \class CFB_FIPS_Mode
//! \brief CFB block cipher mode of operation providing FIPS validated cryptography.
//! \details Requires full block plaintext according to FIPS 800-38A
template <class CIPHER>
struct CFB_FIPS_Mode : public CipherModeDocumentation
{
	typedef CipherModeFinalTemplate_CipherHolder<typename CIPHER::Encryption, ConcretePolicyHolder<Empty, CFB_RequireFullDataBlocks<CFB_EncryptionTemplate<AbstractPolicyHolder<CFB_CipherAbstractPolicy, CFB_ModePolicy> > > > > Encryption;
	typedef CipherModeFinalTemplate_CipherHolder<typename CIPHER::Encryption, ConcretePolicyHolder<Empty, CFB_RequireFullDataBlocks<CFB_DecryptionTemplate<AbstractPolicyHolder<CFB_CipherAbstractPolicy, CFB_ModePolicy> > > > > Decryption;
};

//! \class CFB_FIPS_Mode_ExternalCipher
//! \brief CFB mode, external cipher, providing FIPS validated cryptography.
//! \details Requires full block plaintext according to FIPS 800-38A
struct CFB_FIPS_Mode_ExternalCipher : public CipherModeDocumentation
{
	typedef CipherModeFinalTemplate_ExternalCipher<ConcretePolicyHolder<Empty, CFB_RequireFullDataBlocks<CFB_EncryptionTemplate<AbstractPolicyHolder<CFB_CipherAbstractPolicy, CFB_ModePolicy> > > > > Encryption;
	typedef CipherModeFinalTemplate_ExternalCipher<ConcretePolicyHolder<Empty, CFB_RequireFullDataBlocks<CFB_DecryptionTemplate<AbstractPolicyHolder<CFB_CipherAbstractPolicy, CFB_ModePolicy> > > > > Decryption;
};

CRYPTOPP_DLL_TEMPLATE_CLASS AdditiveCipherTemplate<AbstractPolicyHolder<AdditiveCipherAbstractPolicy, OFB_ModePolicy> >;

//! \class OFB_Mode
//! \brief OFB block cipher mode of operation.
template <class CIPHER>
struct OFB_Mode : public CipherModeDocumentation
{
	typedef CipherModeFinalTemplate_CipherHolder<typename CIPHER::Encryption, ConcretePolicyHolder<Empty, AdditiveCipherTemplate<AbstractPolicyHolder<AdditiveCipherAbstractPolicy, OFB_ModePolicy> > > > Encryption;
	typedef Encryption Decryption;
};

//! \class OFB_Mode_ExternalCipher
//! \brief OFB mode, external cipher.
struct OFB_Mode_ExternalCipher : public CipherModeDocumentation
{
	typedef CipherModeFinalTemplate_ExternalCipher<ConcretePolicyHolder<Empty, AdditiveCipherTemplate<AbstractPolicyHolder<AdditiveCipherAbstractPolicy, OFB_ModePolicy> > > > Encryption;
	typedef Encryption Decryption;
};

CRYPTOPP_DLL_TEMPLATE_CLASS AdditiveCipherTemplate<AbstractPolicyHolder<AdditiveCipherAbstractPolicy, CTR_ModePolicy> >;
CRYPTOPP_DLL_TEMPLATE_CLASS CipherModeFinalTemplate_ExternalCipher<ConcretePolicyHolder<Empty, AdditiveCipherTemplate<AbstractPolicyHolder<AdditiveCipherAbstractPolicy, CTR_ModePolicy> > > >;

//! \class CTR_Mode
//! \brief CTR block cipher mode of operation.
template <class CIPHER>
struct CTR_Mode : public CipherModeDocumentation
{
	typedef CipherModeFinalTemplate_CipherHolder<typename CIPHER::Encryption, ConcretePolicyHolder<Empty, AdditiveCipherTemplate<AbstractPolicyHolder<AdditiveCipherAbstractPolicy, CTR_ModePolicy> > > > Encryption;
	typedef Encryption Decryption;
};

//! \class CTR_Mode_ExternalCipher
//! \brief CTR mode, external cipher.
struct CTR_Mode_ExternalCipher : public CipherModeDocumentation
{
	typedef CipherModeFinalTemplate_ExternalCipher<ConcretePolicyHolder<Empty, AdditiveCipherTemplate<AbstractPolicyHolder<AdditiveCipherAbstractPolicy, CTR_ModePolicy> > > > Encryption;
	typedef Encryption Decryption;
};

//! \class ECB_Mode
//! \brief ECB block cipher mode of operation.
template <class CIPHER>
struct ECB_Mode : public CipherModeDocumentation
{
	typedef CipherModeFinalTemplate_CipherHolder<typename CIPHER::Encryption, ECB_OneWay> Encryption;
	typedef CipherModeFinalTemplate_CipherHolder<typename CIPHER::Decryption, ECB_OneWay> Decryption;
};

CRYPTOPP_DLL_TEMPLATE_CLASS CipherModeFinalTemplate_ExternalCipher<ECB_OneWay>;

//! \class ECB_Mode_ExternalCipher
//! \brief ECB mode, external cipher.
struct ECB_Mode_ExternalCipher : public CipherModeDocumentation
{
	typedef CipherModeFinalTemplate_ExternalCipher<ECB_OneWay> Encryption;
	typedef Encryption Decryption;
};

//! CBC mode
template <class CIPHER>
struct CBC_Mode : public CipherModeDocumentation
{
	typedef CipherModeFinalTemplate_CipherHolder<typename CIPHER::Encryption, CBC_Encryption> Encryption;
	typedef CipherModeFinalTemplate_CipherHolder<typename CIPHER::Decryption, CBC_Decryption> Decryption;
};

CRYPTOPP_DLL_TEMPLATE_CLASS CipherModeFinalTemplate_ExternalCipher<CBC_Encryption>;
CRYPTOPP_DLL_TEMPLATE_CLASS CipherModeFinalTemplate_ExternalCipher<CBC_Decryption>;

//! CBC mode, external cipher
struct CBC_Mode_ExternalCipher : public CipherModeDocumentation
{
	typedef CipherModeFinalTemplate_ExternalCipher<CBC_Encryption> Encryption;
	typedef CipherModeFinalTemplate_ExternalCipher<CBC_Decryption> Decryption;
};

//! CBC mode with ciphertext stealing
template <class CIPHER>
struct CBC_CTS_Mode : public CipherModeDocumentation
{
	typedef CipherModeFinalTemplate_CipherHolder<typename CIPHER::Encryption, CBC_CTS_Encryption> Encryption;
	typedef CipherModeFinalTemplate_CipherHolder<typename CIPHER::Decryption, CBC_CTS_Decryption> Decryption;
};

CRYPTOPP_DLL_TEMPLATE_CLASS CipherModeFinalTemplate_ExternalCipher<CBC_CTS_Encryption>;
CRYPTOPP_DLL_TEMPLATE_CLASS CipherModeFinalTemplate_ExternalCipher<CBC_CTS_Decryption>;

//! \class CBC_CTS_Mode_ExternalCipher
//! \brief CBC mode with ciphertext stealing, external cipher
struct CBC_CTS_Mode_ExternalCipher : public CipherModeDocumentation
{
	typedef CipherModeFinalTemplate_ExternalCipher<CBC_CTS_Encryption> Encryption;
	typedef CipherModeFinalTemplate_ExternalCipher<CBC_CTS_Decryption> Decryption;
};

//#ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY
//typedef CFB_Mode_ExternalCipher::Encryption CFBEncryption;
//typedef CFB_Mode_ExternalCipher::Decryption CFBDecryption;
//typedef OFB_Mode_ExternalCipher::Encryption OFB;
//typedef CTR_Mode_ExternalCipher::Encryption CounterMode;
//#endif

NAMESPACE_END

// Issue 340
#if CRYPTOPP_MSC_VERSION
# pragma warning(pop)
#endif

#if CRYPTOPP_GCC_DIAGNOSTIC_AVAILABLE
# pragma GCC diagnostic pop
#endif

#endif


text:
describe FastlaneSpec::Env do
  # rubocop:disable Style/VariableName
  describe "#with_ARGV" do
    it "temporarily overrides the ARGV values under normal usage" do
      current_ARGV = ARGV.dup
      temp_ARGV = ['temp_inside']
      block_ARGV = nil
      FastlaneSpec::Env.with_ARGV(temp_ARGV) do
        block_ARGV = ARGV.dup
      end
      expect(block_ARGV).to eq(temp_ARGV)
      expect(ARGV).to eq(current_ARGV)
    end

    it "restores ARGV values even if fails in block" do
      current_ARGV = ARGV.dup
      begin
        FastlaneSpec::Env.with_ARGV(['temp_inside']) do
          raise "BOU"
        end
        fail("should not reach here")
      rescue
      end
      expect(ARGV).to eq(current_ARGV)
    end

    it "sets ARGV for good if no block is given" do
      current_ARGV = ARGV.dup
      new_ARGV = ['forever']
      FastlaneSpec::Env.with_ARGV(new_ARGV)
      expect(ARGV).to eq(new_ARGV)
      # reset...
      FastlaneSpec::Env.with_ARGV(current_ARGV)
      expect(ARGV).to eq(current_ARGV)
    end
  end
  # rubocop:enable Style/VariableName
end


text:
<!DOCTYPE html>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Confirm your holadesk account</title>

	Hi,

	Thanks for signing up to holadesk

Click the button bellow to confirm your email.

	Confirm!

                                                                 follow on Twitter | friend on Facebook

																Copyright © 2012 Holalabs, All rights reserved.

																Our contact email is:

																hola@holalabs.com


text:
package fr.openwide.core.infinispan.model.impl;

import java.io.Serializable;
import java.util.Date;

import org.jgroups.Address;

import fr.openwide.core.infinispan.model.IAttribution;

public class Attribution extends AbstractAttribution implements Serializable, IAttribution {

	private static final long serialVersionUID = 2830812408213624466L;

	private Attribution(Address owner, Date attributionDate) {
		super(owner, attributionDate);
	}

	public static final Attribution from(Address owner, Date attributionDate) {
		return new Attribution(owner, attributionDate);
	}

}


text:
<?php

$installer = $this;
/* @var $installer Mage_Sales_Model_Mysql4_Setup */

$installer->startSetup();

$installer->addAttribute('order', 'shipping_tax_amount', array('type'=>'static'));
$installer->addAttribute('order', 'base_shipping_tax_amount', array('type'=>'static'));

$installer->endSetup();


text:
import { ConnectionManager } from "typeorm";
import { Container, Service } from "typedi";
import { Repository } from "typeorm";
import { OrmRepository } from "typeorm-typedi-extensions";
import { User } from "../entity/user";
import { Role } from "../entity/role";
import { Transporter, createTransport, SendMailOptions } from "nodemailer";
import { SmtpOptions } from "nodemailer-smtp-transport";
import { TpMailParameters } from "../timepuncher-variables-server";

const cm = Container.get(ConnectionManager);

@Service()
export class MailerDomain {
    transporter: Transporter;

    constructor() {
        let options: SmtpOptions = {
            port: TpMailParameters.port,
            host: TpMailParameters.host,
            auth: {
                user: TpMailParameters.user,
                pass: TpMailParameters.password
            },
            secure: false,
        }
        this.transporter = createTransport(options);
    }

    sendConfirmationMail(token: string) {
        let sendMailOptions: SendMailOptions = {
            from: TpMailParameters.from,
            to: 'hans.tschan@gmail.com',
            subject: 'Bestätigung Kontoeröffnung',
            html: `<p>Das ist ihr Link zum Bestätigen - bitte klicken Sie <a href='http://localhost:3000/api/v1/register/confirm?confirmation=${token}'>hier</a>, um Ihre E-Mail Adresse zu bestätigen.</p>`
        }

        this.transporter.sendMail(sendMailOptions).then((info) => {
            console.log(info.messageId);
        })
    }
}


text:
# API Authentication (Passport)

- [Introduction](#introduction)
- [Installation](#installation)
    - [Frontend Quickstart](#frontend-quickstart)
    - [Deploying Passport](#deploying-passport)
- [Configuration](#configuration)
    - [Token Lifetimes](#token-lifetimes)
- [Issuing Access Tokens](#issuing-access-tokens)
    - [Managing Clients](#managing-clients)
    - [Requesting Tokens](#requesting-tokens)
    - [Refreshing Tokens](#refreshing-tokens)
- [Password Grant Tokens](#password-grant-tokens)
    - [Creating A Password Grant Client](#creating-a-password-grant-client)
    - [Requesting Tokens](#requesting-password-grant-tokens)
    - [Requesting All Scopes](#requesting-all-scopes)
- [Implicit Grant Tokens](#implicit-grant-tokens)
- [Client Credentials Grant Tokens](#client-credentials-grant-tokens)
- [Personal Access Tokens](#personal-access-tokens)
    - [Creating A Personal Access Client](#creating-a-personal-access-client)
    - [Managing Personal Access Tokens](#managing-personal-access-tokens)
- [Protecting Routes](#protecting-routes)
    - [Via Middleware](#via-middleware)
    - [Passing The Access Token](#passing-the-access-token)
- [Token Scopes](#token-scopes)
    - [Defining Scopes](#defining-scopes)
    - [Assigning Scopes To Tokens](#assigning-scopes-to-tokens)
    - [Checking Scopes](#checking-scopes)
- [Consuming Your API With JavaScript](#consuming-your-api-with-javascript)
- [Events](#events)
- [Testing](#testing)

## Introduction

Laravel already makes it easy to perform authentication via traditional login forms, but what about APIs? APIs typically use tokens to authenticate users and do not maintain session state between requests. Laravel makes API authentication a breeze using Laravel Passport, which provides a full OAuth2 server implementation for your Laravel application in a matter of minutes. Passport is built on top of the [League OAuth2 server](https://github.com/thephpleague/oauth2-server) that is maintained by Alex Bilbie.

> {note} This documentation assumes you are already familiar with OAuth2. If you do not know anything about OAuth2, consider familiarizing yourself with the general terminology and features of OAuth2 before continuing.

## Installation

To get started, install Passport via the Composer package manager:

    composer require laravel/passport

The Passport service provider registers its own database migration directory with the framework, so you should migrate your database after registering the provider. The Passport migrations will create the tables your application needs to store clients and access tokens:

    php artisan migrate

> {note} If you are not going to use Passport's default migrations, you should call the `Passport::ignoreMigrations` method in the `register` method of your `AppServiceProvider`. You may export the default migrations using `php artisan vendor:publish --tag=passport-migrations`.

Next, you should run the `passport:install` command. This command will create the encryption keys needed to generate secure access tokens. In addition, the command will create "personal access" and "password grant" clients which will be used to generate access tokens:

    php artisan passport:install

After running this command, add the `Laravel\Passport\HasApiTokens` trait to your `App\User` model. This trait will provide a few helper methods to your model which allow you to inspect the authenticated user's token and scopes:

    <?php

    namespace App;

    use Laravel\Passport\HasApiTokens;
    use Illuminate\Notifications\Notifiable;
    use Illuminate\Foundation\Auth\User as Authenticatable;

    class User extends Authenticatable
    {
        use HasApiTokens, Notifiable;
    }

Next, you should call the `Passport::routes` method within the `boot` method of your `AuthServiceProvider`. This method will register the routes necessary to issue access tokens and revoke access tokens, clients, and personal access tokens:

    <?php

    namespace App\Providers;

    use Laravel\Passport\Passport;
    use Illuminate\Support\Facades\Gate;
    use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;

    class AuthServiceProvider extends ServiceProvider
    {
        /**
         * The policy mappings for the application.
         *
         * @var array
         */
        protected $policies = [
            'App\Model' => 'App\Policies\ModelPolicy',
        ];

        /**
         * Register any authentication / authorization services.
         *
         * @return void
         */
        public function boot()
        {
            $this->registerPolicies();

            Passport::routes();
        }
    }

Finally, in your `config/auth.php` configuration file, you should set the `driver` option of the `api` authentication guard to `passport`. This will instruct your application to use Passport's `TokenGuard` when authenticating incoming API requests:

    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'api' => [
            'driver' => 'passport',
            'provider' => 'users',
        ],
    ],

### Frontend Quickstart

> {note} In order to use the Passport Vue components, you must be using the [Vue](https://vuejs.org) JavaScript framework. These components also use the Bootstrap CSS framework. However, even if you are not using these tools, the components serve as a valuable reference for your own frontend implementation.

Passport ships with a JSON API that you may use to allow your users to create clients and personal access tokens. However, it can be time consuming to code a frontend to interact with these APIs. So, Passport also includes pre-built [Vue](https://vuejs.org) components you may use as an example implementation or starting point for your own implementation.

To publish the Passport Vue components, use the `vendor:publish` Artisan command:

    php artisan vendor:publish --tag=passport-components

The published components will be placed in your `resources/assets/js/components` directory. Once the components have been published, you should register them in your `resources/assets/js/app.js` file:

    Vue.component(
        'passport-clients',
        require('./components/passport/Clients.vue')
    );

    Vue.component(
        'passport-authorized-clients',
        require('./components/passport/AuthorizedClients.vue')
    );

    Vue.component(
        'passport-personal-access-tokens',
        require('./components/passport/PersonalAccessTokens.vue')
    );

After registering the components, make sure to run `npm run dev` to recompile your assets. Once you have recompiled your assets, you may drop the components into one of your application's templates to get started creating clients and personal access tokens:

    <passport-clients></passport-clients>
    <passport-authorized-clients></passport-authorized-clients>
    <passport-personal-access-tokens></passport-personal-access-tokens>

### Deploying Passport

When deploying Passport to your production servers for the first time, you will likely need to run the `passport:keys` command. This command generates the encryption keys Passport needs in order to generate access token. The generated keys are not typically kept in source control:

    php artisan passport:keys

## Configuration

### Token Lifetimes

By default, Passport issues long-lived access tokens that never need to be refreshed. If you would like to configure a shorter token lifetime, you may use the `tokensExpireIn` and `refreshTokensExpireIn` methods. These methods should be called from the `boot` method of your `AuthServiceProvider`:

    use Carbon\Carbon;

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();

        Passport::routes();

        Passport::tokensExpireIn(Carbon::now()->addDays(15));

        Passport::refreshTokensExpireIn(Carbon::now()->addDays(30));
    }

## Issuing Access Tokens

Using OAuth2 with authorization codes is how most developers are familiar with OAuth2. When using authorization codes, a client application will redirect a user to your server where they will either approve or deny the request to issue an access token to the client.

### Managing Clients

First, developers building applications that need to interact with your application's API will need to register their application with yours by creating a "client". Typically, this consists of providing the name of their application and a URL that your application can redirect to after users approve their request for authorization.

#### The `passport:client` Command

The simplest way to create a client is using the `passport:client` Artisan command. This command may be used to create your own clients for testing your OAuth2 functionality. When you run the `client` command, Passport will prompt you for more information about your client and will provide you with a client ID and secret:

    php artisan passport:client

#### JSON API

Since your users will not be able to utilize the `client` command, Passport provides a JSON API that you may use to create clients. This saves you the trouble of having to manually code controllers for creating, updating, and deleting clients.

However, you will need to pair Passport's JSON API with your own frontend to provide a dashboard for your users to manage their clients. Below, we'll review all of the API endpoints for managing clients. For convenience, we'll use [Axios](https://github.com/mzabriskie/axios) to demonstrate making HTTP requests to the endpoints.

> {tip} If you don't want to implement the entire client management frontend yourself, you can use the [frontend quickstart](#frontend-quickstart) to have a fully functional frontend in a matter of minutes.

#### `GET /oauth/clients`

This route returns all of the clients for the authenticated user. This is primarily useful for listing all of the user's clients so that they may edit or delete them:

    axios.get('/oauth/clients')
        .then(response => {
            console.log(response.data);
        });

#### `POST /oauth/clients`

This route is used to create new clients. It requires two pieces of data: the client's `name` and a `redirect` URL. The `redirect` URL is where the user will be redirected after approving or denying a request for authorization.

When a client is created, it will be issued a client ID and client secret. These values will be used when requesting access tokens from your application. The client creation route will return the new client instance:

    const data = {
        name: 'Client Name',
        redirect: 'http://example.com/callback'
    };

    axios.post('/oauth/clients', data)
        .then(response => {
            console.log(response.data);
        })
        .catch (response => {
            // List errors on response...
        });

#### `PUT /oauth/clients/{client-id}`

This route is used to update clients. It requires two pieces of data: the client's `name` and a `redirect` URL. The `redirect` URL is where the user will be redirected after approving or denying a request for authorization. The route will return the updated client instance:

    const data = {
        name: 'New Client Name',
        redirect: 'http://example.com/callback'
    };

    axios.put('/oauth/clients/' + clientId, data)
        .then(response => {
            console.log(response.data);
        })
        .catch (response => {
            // List errors on response...
        });

#### `DELETE /oauth/clients/{client-id}`

This route is used to delete clients:

    axios.delete('/oauth/clients/' + clientId)
        .then(response => {
            //
        });

### Requesting Tokens

#### Redirecting For Authorization

Once a client has been created, developers may use their client ID and secret to request an authorization code and access token from your application. First, the consuming application should make a redirect request to your application's `/oauth/authorize` route like so:

    Route::get('/redirect', function () {
        $query = http_build_query([
            'client_id' => 'client-id',
            'redirect_uri' => 'http://example.com/callback',
            'response_type' => 'code',
            'scope' => '',
        ]);

        return redirect('http://your-app.com/oauth/authorize?'.$query);
    });

> {tip} Remember, the `/oauth/authorize` route is already defined by the `Passport::routes` method. You do not need to manually define this route.

#### Approving The Request

When receiving authorization requests, Passport will automatically display a template to the user allowing them to approve or deny the authorization request. If they approve the request, they will be redirected back to the `redirect_uri` that was specified by the consuming application. The `redirect_uri` must match the `redirect` URL that was specified when the client was created.

If you would like to customize the authorization approval screen, you may publish Passport's views using the `vendor:publish` Artisan command. The published views will be placed in `resources/views/vendor/passport`:

    php artisan vendor:publish --tag=passport-views

#### Converting Authorization Codes To Access Tokens

If the user approves the authorization request, they will be redirected back to the consuming application. The consumer should then issue a `POST` request to your application to request an access token. The request should include the authorization code that was issued by your application when the user approved the authorization request. In this example, we'll use the Guzzle HTTP library to make the `POST` request:

    Route::get('/callback', function (Request $request) {
        $http = new GuzzleHttp\Client;

        $response = $http->post('http://your-app.com/oauth/token', [
            'form_params' => [
                'grant_type' => 'authorization_code',
                'client_id' => 'client-id',
                'client_secret' => 'client-secret',
                'redirect_uri' => 'http://example.com/callback',
                'code' => $request->code,
            ],
        ]);

        return json_decode((string) $response->getBody(), true);
    });

This `/oauth/token` route will return a JSON response containing `access_token`, `refresh_token`, and `expires_in` attributes. The `expires_in` attribute contains the number of seconds until the access token expires.

> {tip} Like the `/oauth/authorize` route, the `/oauth/token` route is defined for you by the `Passport::routes` method. There is no need to manually define this route.

### Refreshing Tokens

If your application issues short-lived access tokens, users will need to refresh their access tokens via the refresh token that was provided to them when the access token was issued. In this example, we'll use the Guzzle HTTP library to refresh the token:

    $http = new GuzzleHttp\Client;

    $response = $http->post('http://your-app.com/oauth/token', [
        'form_params' => [
            'grant_type' => 'refresh_token',
            'refresh_token' => 'the-refresh-token',
            'client_id' => 'client-id',
            'client_secret' => 'client-secret',
            'scope' => '',
        ],
    ]);

    return json_decode((string) $response->getBody(), true);

This `/oauth/token` route will return a JSON response containing `access_token`, `refresh_token`, and `expires_in` attributes. The `expires_in` attribute contains the number of seconds until the access token expires.

## Password Grant Tokens

The OAuth2 password grant allows your other first-party clients, such as a mobile application, to obtain an access token using an e-mail address / username and password. This allows you to issue access tokens securely to your first-party clients without requiring your users to go through the entire OAuth2 authorization code redirect flow.

### Creating A Password Grant Client

Before your application can issue tokens via the password grant, you will need to create a password grant client. You may do this using the `passport:client` command with the `--password` option. If you have already run the `passport:install` command, you do not need to run this command:

    php artisan passport:client --password

### Requesting Tokens

Once you have created a password grant client, you may request an access token by issuing a `POST` request to the `/oauth/token` route with the user's email address and password. Remember, this route is already registered by the `Passport::routes` method so there is no need to define it manually. If the request is successful, you will receive an `access_token` and `refresh_token` in the JSON response from the server:

    $http = new GuzzleHttp\Client;

    $response = $http->post('http://your-app.com/oauth/token', [
        'form_params' => [
            'grant_type' => 'password',
            'client_id' => 'client-id',
            'client_secret' => 'client-secret',
            'username' => 'taylor@laravel.com',
            'password' => 'my-password',
            'scope' => '',
        ],
    ]);

    return json_decode((string) $response->getBody(), true);

> {tip} Remember, access tokens are long-lived by default. However, you are free to [configure your maximum access token lifetime](#configuration) if needed.

### Requesting All Scopes

When using the password grant, you may wish to authorize the token for all of the scopes supported by your application. You can do this by requesting the `*` scope. If you request the `*` scope, the `can` method on the token instance will always return `true`. This scope may only be assigned to a token that is issued using the `password` grant:

    $response = $http->post('http://your-app.com/oauth/token', [
        'form_params' => [
            'grant_type' => 'password',
            'client_id' => 'client-id',
            'client_secret' => 'client-secret',
            'username' => 'taylor@laravel.com',
            'password' => 'my-password',
            'scope' => '*',
        ],
    ]);

## Implicit Grant Tokens

The implicit grant is similar to the authorization code grant; however, the token is returned to the client without exchanging an authorization code. This grant is most commonly used for JavaScript or mobile applications where the client credentials can't be securely stored. To enable the grant, call the `enableImplicitGrant` method in your `AuthServiceProvider`:

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();

        Passport::routes();

        Passport::enableImplicitGrant();
    }

Once a grant has been enabled, developers may use their client ID to request an access token from your application. The consuming application should make a redirect request to your application's `/oauth/authorize` route like so:

    Route::get('/redirect', function () {
        $query = http_build_query([
            'client_id' => 'client-id',
            'redirect_uri' => 'http://example.com/callback',
            'response_type' => 'token',
            'scope' => '',
        ]);

        return redirect('http://your-app.com/oauth/authorize?'.$query);
    });

> {tip} Remember, the `/oauth/authorize` route is already defined by the `Passport::routes` method. You do not need to manually define this route.

## Client Credentials Grant Tokens

The client credentials grant is suitable for machine-to-machine authentication. For example, you might use this grant in a scheduled job which is performing maintenance tasks over an API. To use this method you first need to add new middleware to your `$routeMiddleware` in `app/Http/Kernel.php`:

    use Laravel\Passport\Http\Middleware\CheckClientCredentials;

    protected $routeMiddleware = [
        'client' => CheckClientCredentials::class,
    ];

Then attach this middleware to a route:

    Route::get('/user', function(Request $request) {
        ...
    })->middleware('client');

To retrieve a token, make a request to the `oauth/token` endpoint:

    $guzzle = new GuzzleHttp\Client;

    $response = $guzzle->post('http://your-app.com/oauth/token', [
        'form_params' => [
            'grant_type' => 'client_credentials',
            'client_id' => 'client-id',
            'client_secret' => 'client-secret',
            'scope' => 'your-scope',
        ],
    ]);

    return json_decode((string) $response->getBody(), true)['access_token'];

## Personal Access Tokens

Sometimes, your users may want to issue access tokens to themselves without going through the typical authorization code redirect flow. Allowing users to issue tokens to themselves via your application's UI can be useful for allowing users to experiment with your API or may serve as a simpler approach to issuing access tokens in general.

> {note} Personal access tokens are always long-lived. Their lifetime is not modified when using the `tokensExpireIn` or `refreshTokensExpireIn` methods.

### Creating A Personal Access Client

Before your application can issue personal access tokens, you will need to create a personal access client. You may do this using the `passport:client` command with the `--personal` option. If you have already run the `passport:install` command, you do not need to run this command:

    php artisan passport:client --personal

### Managing Personal Access Tokens

Once you have created a personal access client, you may issue tokens for a given user using the `createToken` method on the `User` model instance. The `createToken` method accepts the name of the token as its first argument and an optional array of [scopes](#token-scopes) as its second argument:

    $user = App\User::find(1);

    // Creating a token without scopes...
    $token = $user->createToken('Token Name')->accessToken;

    // Creating a token with scopes...
    $token = $user->createToken('My Token', ['place-orders'])->accessToken;

#### JSON API

Passport also includes a JSON API for managing personal access tokens. You may pair this with your own frontend to offer your users a dashboard for managing personal access tokens. Below, we'll review all of the API endpoints for managing personal access tokens. For convenience, we'll use [Axios](https://github.com/mzabriskie/axios) to demonstrate making HTTP requests to the endpoints.

> {tip} If you don't want to implement the personal access token frontend yourself, you can use the [frontend quickstart](#frontend-quickstart) to have a fully functional frontend in a matter of minutes.

#### `GET /oauth/scopes`

This route returns all of the [scopes](#token-scopes) defined for your application. You may use this route to list the scopes a user may assign to a personal access token:

    axios.get('/oauth/scopes')
        .then(response => {
            console.log(response.data);
        });

#### `GET /oauth/personal-access-tokens`

This route returns all of the personal access tokens that the authenticated user has created. This is primarily useful for listing all of the user's tokens so that they may edit or delete them:

    axios.get('/oauth/personal-access-tokens')
        .then(response => {
            console.log(response.data);
        });

#### `POST /oauth/personal-access-tokens`

This route creates new personal access tokens. It requires two pieces of data: the token's `name` and the `scopes` that should be assigned to the token:

    const data = {
        name: 'Token Name',
        scopes: []
    };

    axios.post('/oauth/personal-access-tokens', data)
        .then(response => {
            console.log(response.data.accessToken);
        })
        .catch (response => {
            // List errors on response...
        });

#### `DELETE /oauth/personal-access-tokens/{token-id}`

This route may be used to delete personal access tokens:

    axios.delete('/oauth/personal-access-tokens/' + tokenId);

## Protecting Routes

### Via Middleware

Passport includes an [authentication guard](/docs/{{version}}/authentication#adding-custom-guards) that will validate access tokens on incoming requests. Once you have configured the `api` guard to use the `passport` driver, you only need to specify the `auth:api` middleware on any routes that require a valid access token:

    Route::get('/user', function () {
        //
    })->middleware('auth:api');

### Passing The Access Token

When calling routes that are protected by Passport, your application's API consumers should specify their access token as a `Bearer` token in the `Authorization` header of their request. For example, when using the Guzzle HTTP library:

    $response = $client->request('GET', '/api/user', [
        'headers' => [
            'Accept' => 'application/json',
            'Authorization' => 'Bearer '.$accessToken,
        ],
    ]);

## Token Scopes

### Defining Scopes

Scopes allow your API clients to request a specific set of permissions when requesting authorization to access an account. For example, if you are building an e-commerce application, not all API consumers will need the ability to place orders. Instead, you may allow the consumers to only request authorization to access order shipment statuses. In other words, scopes allow your application's users to limit the actions a third-party application can perform on their behalf.

You may define your API's scopes using the `Passport::tokensCan` method in the `boot` method of your `AuthServiceProvider`. The `tokensCan` method accepts an array of scope names and scope descriptions. The scope description may be anything you wish and will be displayed to users on the authorization approval screen:

    use Laravel\Passport\Passport;

    Passport::tokensCan([
        'place-orders' => 'Place orders',
        'check-status' => 'Check order status',
    ]);

### Assigning Scopes To Tokens

#### When Requesting Authorization Codes

When requesting an access token using the authorization code grant, consumers should specify their desired scopes as the `scope` query string parameter. The `scope` parameter should be a space-delimited list of scopes:

    Route::get('/redirect', function () {
        $query = http_build_query([
            'client_id' => 'client-id',
            'redirect_uri' => 'http://example.com/callback',
            'response_type' => 'code',
            'scope' => 'place-orders check-status',
        ]);

        return redirect('http://your-app.com/oauth/authorize?'.$query);
    });

#### When Issuing Personal Access Tokens

If you are issuing personal access tokens using the `User` model's `createToken` method, you may pass the array of desired scopes as the second argument to the method:

    $token = $user->createToken('My Token', ['place-orders'])->accessToken;

### Checking Scopes

Passport includes two middleware that may be used to verify that an incoming request is authenticated with a token that has been granted a given scope. To get started, add the following middleware to the `$routeMiddleware` property of your `app/Http/Kernel.php` file:

    'scopes' => \Laravel\Passport\Http\Middleware\CheckScopes::class,
    'scope' => \Laravel\Passport\Http\Middleware\CheckForAnyScope::class,

#### Check For All Scopes

The `scopes` middleware may be assigned to a route to verify that the incoming request's access token has *all* of the listed scopes:

    Route::get('/orders', function () {
        // Access token has both "check-status" and "place-orders" scopes...
    })->middleware('scopes:check-status,place-orders');

#### Check For Any Scopes

The `scope` middleware may be assigned to a route to verify that the incoming request's access token has *at least one* of the listed scopes:

    Route::get('/orders', function () {
        // Access token has either "check-status" or "place-orders" scope...
    })->middleware('scope:check-status,place-orders');

#### Checking Scopes On A Token Instance

Once an access token authenticated request has entered your application, you may still check if the token has a given scope using the `tokenCan` method on the authenticated `User` instance:

    use Illuminate\Http\Request;

    Route::get('/orders', function (Request $request) {
        if ($request->user()->tokenCan('place-orders')) {
            //
        }
    });

## Consuming Your API With JavaScript

When building an API, it can be extremely useful to be able to consume your own API from your JavaScript application. This approach to API development allows your own application to consume the same API that you are sharing with the world. The same API may be consumed by your web application, mobile applications, third-party applications, and any SDKs that you may publish on various package managers.

Typically, if you want to consume your API from your JavaScript application, you would need to manually send an access token to the application and pass it with each request to your application. However, Passport includes a middleware that can handle this for you. All you need to do is add the `CreateFreshApiToken` middleware to your `web` middleware group:

    'web' => [
        // Other middleware...
        \Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
    ],

This Passport middleware will attach a `laravel_token` cookie to your outgoing responses. This cookie contains an encrypted JWT that Passport will use to authenticate API requests from your JavaScript application. Now, you may make requests to your application's API without explicitly passing an access token:

    axios.get('/api/user')
        .then(response => {
            console.log(response.data);
        });

When using this method of authentication, Axios will automatically send the `X-CSRF-TOKEN` header. In addition, the default Laravel JavaScript scaffolding instructs Axios to send the `X-Requested-With` header:

    window.axios.defaults.headers.common = {
        'X-Requested-With': 'XMLHttpRequest',
    };

> {note} If you are using a different JavaScript framework, you should make sure it is configured to send the `X-CSRF-TOKEN` and `X-Requested-With` headers with every outgoing request.

## Events

Passport raises events when issuing access tokens and refresh tokens. You may use these events to prune or revoke other access tokens in your database. You may attach listeners to these events in your application's `EventServiceProvider`:

```php
/**
 * The event listener mappings for the application.
 *
 * @var array
 */
protected $listen = [
    'Laravel\Passport\Events\AccessTokenCreated' => [
        'App\Listeners\RevokeOldTokens',
    ],

    'Laravel\Passport\Events\RefreshTokenCreated' => [
        'App\Listeners\PruneOldTokens',
    ],
];
```

## Testing

Passport's `actingAs` method may be used to specify the currently authenticated user as well as its scopes. The first argument given to the `actingAs` method is the user instance and the second is an array of scopes that should be granted to the user's token:

    public function testServerCreation()
    {
        Passport::actingAs(
            factory(User::class)->create(),
            ['create-servers']
        );

        $response = $this->post('/api/create-server');

        $response->assertStatus(200);
    }


text:
package de.jtem.jrworkspace.plugin.lnfswitch;

import javax.swing.JPanel;

import de.jtem.jrworkspace.plugin.Controller;
import de.jtem.jrworkspace.plugin.Plugin;
import de.jtem.jrworkspace.plugin.PluginInfo;
import de.jtem.jrworkspace.plugin.lnfswitch.image.ImageHook;

public abstract class LookAndFeelPlugin extends Plugin {

	protected LookAndFeelSwitch
		lookAndFeelSwitch = null;

	public abstract String getLnFName();

	public abstract String getLnFClassName();

	public abstract boolean isSupported();

	public JPanel getOptionPanel() {
		return null;
	}

	@Override
	public PluginInfo getPluginInfo() {
		PluginInfo info = new PluginInfo();
		info.name = getClass().getName();
		info.icon = ImageHook.getIcon("pictures.png");
		return info;
	}

	@Override
	public void install(Controller c) throws Exception {
		super.install(c);
		lookAndFeelSwitch = c.getPlugin(LookAndFeelSwitch.class);
		if (isSupported()) {
			lookAndFeelSwitch.addLookAndFeel(this);
		}
	}

	@Override
	public void uninstall(Controller c) throws Exception {
		super.uninstall(c);
		lookAndFeelSwitch.removeLookAndFeel(this);
	}

	@Override
	public String toString() {
		return getLnFName();
	}

}


text:
class ChangeDexcriptionFormatInPrinciples < ActiveRecord::Migration
  def up
  	change_column :principles, :description, :text
  end

  def down
  	change_column :principles, :description, :string
  end
end


text:
using System;
using System.Diagnostics;
using NHibernate.Mapping.ByCode;
using NodaTime;

namespace Dematt.Airy.Nhibernate.NodaTime.Helpers
{
    /// <summary>
    /// Provides helper methods for setting up NHibernate ModelMapper classes to map NodaTime types.
    /// </summary>
    /// <remarks>THIS DOES NOT WORK AS IT TRIES TO MAP THE CLASSES THAT MAKE UP OFFSETDATETIME RATHER THAN OFFSETDATETIME ITSELF.</remarks>
    [Obsolete]
    public static class NodaTimeMapperHelper
    {
        /// <summary>
        /// Applies the <see cref="OffsetDateTimeType"/> UserType to all <see cref="OffsetDateTime"/> fields in the mapping.
        /// </summary>
        /// <remarks>
        /// Allows the use of <see cref="OffsetDateTime"/> type with databases that do not natively support it.
        /// User: mapper.BeforeMapProperty += NodaTimeMapperHelper.ApplyOffsetDateTimeType
        /// </remarks>
        public static void ApplyOffsetDateTimeType(IModelInspector inspector, PropertyPath property, IPropertyMapper mapper)
        {
            var root = property.GetRootMember();
            Debug.WriteLine(root.Name);
            Type propertyType = property.LocalMember.GetPropertyOrFieldType();
            if (propertyType == typeof(OffsetDateTime) || propertyType == typeof(OffsetDateTime?))
            {
                mapper.Type<OffsetDateTimeType>();
            }
        }
    }
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Docs</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta name="description" content="">
  <meta name="author" content="">

  <meta content="IE=edge,chrome=1" http-equiv="X-UA-Compatible">

  <title>Docs</title>

  <link href="stylesheets/application.css" media="screen" rel="stylesheet" type="text/css" />

      <button type="button" class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">

      </button>

      Docs

                Home

                Files

                Layout

                Widgets

                Help

Help

I only covered the most important components of this theme. If you have any questions, feel free to contact me through the contact form that {wrap}bootstrap provides

Be sure to mention the License ID you got through your purchase

Have you found a bug in this theme? Send me a message and let me know what your issue is. I'll do my best to help you

What's covered by support:

Upgrades to latest version of Twitter Bootstrap

Bug fixes for components created by me

Issues related to cross browser support in my themes

Limited how-to advice and customization direction

What's not covered by support:

Fixing errors or bugs with Twitter Bootstrap

In-depth theme customization

Addition of functionality not included by default

Any errors relating to theme customization.


text:
@interface MWBalanceHeaderView : UIView

@property (nonatomic, strong) UIImageView *backImageView;

@property (nonatomic, copy)NSString *balance;

@end


text:
require 'abstract_unit'
require 'active_support/logger'
require 'active_support/tagged_logging'

class TaggedLoggingTest < ActiveSupport::TestCase
  class MyLogger < ::ActiveSupport::Logger
    def flush(*)
      info "[FLUSHED]"
    end
  end

  setup do
    @output = StringIO.new
    @logger = ActiveSupport::TaggedLogging.new(MyLogger.new(@output))
  end

  test 'sets logger.formatter if missing and extends it with a tagging API' do
    logger = Logger.new(StringIO.new)
    assert_nil logger.formatter
    ActiveSupport::TaggedLogging.new(logger)
    assert_not_nil logger.formatter
    assert logger.formatter.respond_to?(:tagged)
  end

  test "tagged once" do
    @logger.tagged("BCX") { @logger.info "Funky time" }
    assert_equal "[BCX] Funky time\n", @output.string
  end

  test "tagged twice" do
    @logger.tagged("BCX") { @logger.tagged("Jason") { @logger.info "Funky time" } }
    assert_equal "[BCX] [Jason] Funky time\n", @output.string
  end

  test "tagged thrice at once" do
    @logger.tagged("BCX", "Jason", "New") { @logger.info "Funky time" }
    assert_equal "[BCX] [Jason] [New] Funky time\n", @output.string
  end

  test "tagged are flattened" do
    @logger.tagged("BCX", %w(Jason New)) { @logger.info "Funky time" }
    assert_equal "[BCX] [Jason] [New] Funky time\n", @output.string
  end

  test "push and pop tags directly" do
    assert_equal %w(A B C), @logger.push_tags('A', ['B', '  ', ['C']])
    @logger.info 'a'
    assert_equal %w(C), @logger.pop_tags
    @logger.info 'b'
    assert_equal %w(B), @logger.pop_tags(1)
    @logger.info 'c'
    assert_equal [], @logger.clear_tags!
    @logger.info 'd'
    assert_equal "[A] [B] [C] a\n[A] [B] b\n[A] c\nd\n", @output.string
  end

  test "does not strip message content" do
    @logger.info "  Hello"
    assert_equal "  Hello\n", @output.string
  end

  test "provides access to the logger instance" do
    @logger.tagged("BCX") { |logger| logger.info "Funky time" }
    assert_equal "[BCX] Funky time\n", @output.string
  end

  test "tagged once with blank and nil" do
    @logger.tagged(nil, "", "New") { @logger.info "Funky time" }
    assert_equal "[New] Funky time\n", @output.string
  end

  test "keeps each tag in their own thread" do
    @logger.tagged("BCX") do
      Thread.new do
        @logger.tagged("OMG") { @logger.info "Cool story bro" }
      end.join
      @logger.info "Funky time"
    end
    assert_equal "[OMG] Cool story bro\n[BCX] Funky time\n", @output.string
  end

  test "cleans up the taggings on flush" do
    @logger.tagged("BCX") do
      Thread.new do
        @logger.tagged("OMG") do
          @logger.flush
          @logger.info "Cool story bro"
        end
      end.join
    end
    assert_equal "[FLUSHED]\nCool story bro\n", @output.string
  end

  test "mixed levels of tagging" do
    @logger.tagged("BCX") do
      @logger.tagged("Jason") { @logger.info "Funky time" }
      @logger.info "Junky time!"
    end

    assert_equal "[BCX] [Jason] Funky time\n[BCX] Junky time!\n", @output.string
  end
end