text:
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Package jpeg implements a JPEG image decoder and encoder.
//
// JPEG is defined in ITU-T T.81: http://www.w3.org/Graphics/JPEG/itu-t81.pdf.
//
#include <sirikata/core/jpeg-arhc/Decoder.hpp>
namespace Sirikata {

struct TableSelector {
	uint8 compIndex;
	uint8 td; // DC table selector.
	uint8 ta; // AC table selector.
};
// Specified in section B.2.3.
JpegError Decoder::processSOS(int n) {
    Decoder &d = *this;
	if (d.nComp == 0) {
		return JpegErrorFormatError("missing SOF marker");
	}
	if (n < 6 || 4+2*d.nComp < n || n%2 != 0) {
        return JpegErrorFormatError("SOS has wrong length");
	}
    JpegError err;
	if ((err = d.readFull(d.tmp, n)) != JpegError::nil()) {
		return err;
	}
	int nComp = (int)(d.tmp[0]);
	if (n != 4+2*nComp) {
		return JpegErrorFormatError("SOS length inconsistent with number of components");
	}
	TableSelector  scan[nColorComponent];

	for (int i = 0; i < nComp; i++) {
		uint8 cs = d.tmp[1+2*i]; // Component selector.
        int32 compIndex = -1;
        for (int j = 0; j < nColorComponent; ++j) {
            component xcomp = d.comp[j];
			if (cs == xcomp.c) {
				compIndex = j;
			}
		}
		if (compIndex < 0) {
			return JpegErrorFormatError("unknown component selector");
		}
		scan[i].compIndex = uint8(compIndex);
		scan[i].td = d.tmp[2+2*i] >> 4;
		if (scan[i].td > maxTh) {
			return JpegErrorFormatError("bad Td value");
		}
		scan[i].ta = d.tmp[2+2*i] & 0x0f;
		if (scan[i].ta > maxTh) {
			return JpegErrorFormatError("bad Ta value");
		}
	}

	// zigStart and zigEnd are the spectral selection bounds.
	// ah and al are the successive approximation high and low values.
	// The spec calls these values Ss, Se, Ah and Al.
	//
	// For (progressive JPEGs, these are the two more-or-less independent
	// aspects of progression. Spectral selection progression is when not
	// all of a block's 64 DCT coefficients are transmitted in one pass.
	// For (example, three passes could transmit coefficient 0 (the DC
	// component), coefficients 1-5, and coefficients 6-63, in zig-zag
	// order. Successive approximation is when not all of the bits of a
	// band of coefficients are transmitted in one pass. For (example,
	// three passes could transmit the 6 most significant bits, followed
	// by the second-least significant bit, followed by the least
	// significant bit.
	//
	// For (baseline JPEGs, these parameters are hard-coded to 0/63/0/0.
	int32 zigStart = 0;
    int32 zigEnd = JpegBlock::blockSize - 1;
    uint32 ah = 0;
    uint32 al = 0;
	if (d.progressive) {
		zigStart = int32(d.tmp[1+2*nComp]);
		zigEnd = int32(d.tmp[2+2*nComp]);
		ah = uint32(d.tmp[3+2*nComp] >> 4);
		al = uint32(d.tmp[3+2*nComp] & 0x0f);
		if ((zigStart == 0 && zigEnd != 0) || zigStart > zigEnd || JpegBlock::blockSize <= zigEnd) {
			return JpegErrorFormatError("bad spectral selection bounds");
		}
		if (zigStart != 0 && nComp != 1) {
			return JpegErrorFormatError("progressive AC coefficients for (more than one component");
		}
		if (ah != 0 && ah != al+1) {
			return JpegErrorFormatError("bad successive approximation values");
		}
	}

	// mxx and myy are the number of MCUs (Minimum Coded Units) in the image.
	int h0 = d.comp[0].h;
    int v0 = d.comp[0].v; // The h and v values from the Y components.
    int mxx = (d.width + 8*h0 - 1) / (8 * h0);
    int myy = (d.height + 8*v0 - 1) / (8 * v0);
	if (d.progressive) {
		for (int i = 0; i < nComp; i++) {
			uint8 compIndex = scan[i].compIndex;
			if (d.progCoeffs[compIndex].empty()) {
				d.progCoeffs[compIndex].reserve(mxx*myy*d.comp[compIndex].h*d.comp[compIndex].v);
			}
		}
	}

	d.bits = Bits();
	int mcu = 0;
    uint8 expectedRST = uint8(rst0Marker);
    JpegBlock b;
    int32 dc[nColorComponent] = {0};
    int bx = 0;
    int by = 0;
    int blockCount = 0;
    for (int my = 0; my < myy; my++) {
        for (int mx = 0; mx < mxx; mx++) {
			d.huffTransSect = true;
			for (int i = 0; i < nComp; i++) {
                uint8 compIndex = scan[i].compIndex;
                JpegBlock *qt = &d.quant[d.comp[compIndex].tq];
                (void) qt;
				for (int j = 0; j < d.comp[compIndex].h*d.comp[compIndex].v; j++) {
					// The blocks are traversed one MCU at a time. For (4:2:0 chroma
					// subsampling, there are four Y 8x8 blocks in every 16x16 MCU.
					//
					// For (a baseline 32x16 pixel image, the Y blocks visiting order is:
					//	0 1 4 5
					//	2 3 6 7
					//
					// For (progressive images, the interleaved scans (those with nComp > 1)
					// are traversed as above, but non-interleaved scans are traversed left
					// to right, top to bottom:
					//	0 1 2 3
					//	4 5 6 7
					// Only DC scans (zigStart == 0) can be interleaved. AC scans must have
					// only one component.
					//
					// To further complicate matters, for (non-interleaved scans, there is no
					// data for (any blocks that are inside the image at the MCU level but
					// outside the image at the pixel level. For (example, a 24x16 pixel 4:2:0
					// progressive image consists of two 16x16 MCUs. The interleaved scans
					// will process 8 Y blocks:
					//	0 1 4 5
					//	2 3 6 7
					// The non-interleaved scans will process only 6 Y blocks:
					//	0 1 2
					//	3 4 5
					if (nComp != 1) {
						bx = d.comp[compIndex].h*mx;
                        by = d.comp[compIndex].v*my;
						if (h0 == 1) {
                            by += j;
						} else {
							bx += j % 2;
							by += j / 2;
						}
					} else {
                        int q = mxx * d.comp[compIndex].h;
						bx = blockCount % q;
						by = blockCount / q;
						blockCount++;
                        if (bx*8 >= d.width || by*8 >= d.height) {
							continue;
						}
					}

					// Load the previous partially decoded coefficients, if (applicable.
					if (d.progressive) {
						b = d.progCoeffs[compIndex][by*mxx*d.comp[compIndex].h+bx];
					} else {
						b = JpegBlock();
					}
					if (ah != 0) {
                        JpegError err;
						if ((err = d.refine(&b, &d.huff[acTable][scan[i].ta], zigStart, zigEnd, 1<<al, i)) != JpegError::nil()) {
                            d.wbuffer.flushBits(true);
							return err;
						}
					} else {
						int zig = zigStart;
                        if (zig == 0) {
                            zig++;
							// Decode the DC coefficient, as specified in section F.2.2.1.
                            std::pair<uint8, JpegError>valueErr = d.decodeHuffman(&d.huff[dcTable][scan[i].td], zig-1, i);
							if (valueErr.second != JpegError::nil()) {
                                d.wbuffer.flushBits(true);
								return valueErr.second;
							}
							if (valueErr.first > 16) {
                                d.wbuffer.flushBits(true);
								return JpegErrorUnsupportedError("excessive DC component");
							}
							std::pair<int32, JpegError>dcDeltaErr = d.receiveExtend(valueErr.first);
							if (dcDeltaErr.second != JpegError::nil()) {
                                d.wbuffer.flushBits(true);
								return dcDeltaErr.second;
							}
							dc[compIndex] += dcDeltaErr.first;
							b[0] = dc[compIndex] << al;
						}

						if (zig <= zigEnd && d.eobRun > 0) {
							d.eobRun--;
						} else {
							// Decode the AC coefficients, as specified in section F.2.2.2.
                            huffman *huff = &d.huff[acTable][scan[i].ta];
							for (; zig <= zigEnd; zig++) {
                                uint8E valueErr = d.decodeHuffman(huff, zig, i /*component*/);
								if (valueErr.second != JpegError::nil()) {
                                    d.wbuffer.flushBits(true);
									return valueErr.second;
								}
                                uint8 val0 = valueErr.first >> 4;
                                uint8 val1 = valueErr.first & 0x0f;
								if (val1 != 0) {
                                    zig += int32(val0);
									if (zig > zigEnd) {
										break;
									}
									int32E acErr = d.receiveExtend(val1);
									if (acErr.second != JpegError::nil()) {
                                        d.wbuffer.flushBits(true);
										return acErr.second;
									}
									b[unzig()[zig]] = acErr.first << al;
								} else {
									if (val0 != 0x0f) {
										d.eobRun = uint16(1 << val0);
										if (val0 != 0) {
											uint32E bitsErr = d.decodeBits(int32(val0));
											if (bitsErr.second != JpegError::nil()) {
                                                    d.wbuffer.flushBits(true);
                                                    return bitsErr.second;
											}
                                            d.eobRun |= (uint16)bitsErr.first;
										}
										d.eobRun--;
										break;
									}
									zig += 0x0f;
								}
							}
						}
					}

					if (d.progressive) {
						if (zigEnd != JpegBlock::blockSize-1 || al != 0) {
							// We haven't completely decoded this 8x8 block. Save the coefficients.
							d.progCoeffs[compIndex][by*mxx*d.comp[compIndex].h+bx] = b;
							// At this point, we could execute the rest of the loop body to dequantize and
							// perform the inverse DCT, to save early stages of a progressive image to the
							// *image.YCbCr buffers (the whole point of progressive encoding), but in Go,
							// the jpeg.Decode function does not return until the entire image is decoded,
							// so we "continue" here to avoid wasted computation.
							continue;
						}
					}
				} // for (j
			} // for (i
            d.huffTransSect = false;
            mcu++;
            if (d.ri > 0 && mcu%d.ri == 0 && mcu < mxx*myy) {
				// if (any bits are outstanding at this time, we must flush them now
                d.wbuffer.flushBits(true);
                // A more sophisticated decoder could use RST[0-7] markers to resynchronize from corrupt input,
                // but this one assumes well-formed input, and hence the restart marker follows immediately.
                if ((err = d.readFull(d.tmp, 2)) != JpegError::nil()) {
                    d.wbuffer.flushBits(true);
                    return err;
                }
                //fprintf(stderr, "Expected Restart marker %x\n", d.tmp);
                if (d.tmp[0] != 0xff || d.tmp[1] != expectedRST) {
                    d.wbuffer.flushBits(true);
                    return JpegErrorFormatError("bad RST marker");
                }
                expectedRST++;
                if (expectedRST == rst7Marker+1) {
                    expectedRST = rst0Marker;
                }
                // Reset the Huffman decoder.
                d.bits = Bits();
                // Reset the DC components, as per section F.2.1.3.1.
                memset(dc, 0, sizeof(int32) * nColorComponent);
                // Reset the progressive decoder state, as per section G.1.2.2.
                d.eobRun = 0;
            }
        } // for (mx
	} // for (my
    d.wbuffer.flushBits(true);
	return JpegError::nil();
}

// refine decodes a successive approximation refinement block, as specified in
// section G.1.2.
JpegError Decoder::refine(JpegBlock* b, huffman* h, int32 zigStart, int32 zigEnd, int32 delta, int component) {
    Decoder & d = *this;
	// Refining a DC component is trivial.
	if (zigStart == 0) {
		if (zigEnd != 0) {
			assert(false && "unreachable");
		}
		uint32E bitErr = d.decodeBit();
		if (bitErr.second != JpegError::nil()) {
			return bitErr.second;
		}
        if (bitErr.first) {
			(*b)[0] |= delta;
		}
		return JpegError::nil();
	}

	// Refining AC components is more complicated; see sections G.1.2.2 and G.1.2.3.
    int32 zig = zigStart;
	if (d.eobRun == 0) {
		for (; zig <= zigEnd; zig++) {
            int32 z = 0;
			uint8E valueErr = d.decodeHuffman(h, zig, component);
            if (valueErr.second != JpegError::nil()) {
				return valueErr.second;
			}
            uint8 val0 = valueErr.first >> 4;
			uint8 val1 = valueErr.first & 0x0f;

			if (val1 == 0) {
              if (val0 != 0x0f) {
                  d.eobRun = uint16(1 << val0);
                  if (val0 != 0) {
                      uint32E bitsErr = d.decodeBits(int32(val0));
                      if (bitsErr.second != JpegError::nil()) {
                          return bitsErr.second;
                      }
                      d.eobRun |= (uint16)(bitsErr.first);
                  }
                  break;
              }
            } else if (val1 == 1) {
              z = delta;
              {
                  uint8E bitErr = d.decodeBit();
                  if (bitErr.second != JpegError::nil()) {
                      return bitErr.second;
                  }
                  if (!bitErr.first) {
                      z = -z;
                  }
              }
            } else {
              return JpegErrorFormatError("unexpected Huffman code");
			}
			int32E zigErr = d.refineNonZeroes(b, zig, zigEnd, int32(val0), delta);
			if (zigErr.second != JpegError::nil()) {
				return zigErr.second;
			}
            zig = zigErr.first;
			if (zig > zigEnd) {
				return JpegErrorFormatError("too many coefficients");
			}
			if (z != 0) {
                (*b)[unzig()[zig]] = z;
			}
		}
	}
	if (d.eobRun > 0) {
		d.eobRun--;
        int32E zigErr;
		if ((zigErr = d.refineNonZeroes(b, zig, zigEnd, -1, delta)).second != JpegError::nil()) {
			return zigErr.second;
		}
	}
	return JpegError::nil();
}

// refineNonZeroes refines non-zero entries of b in zig-zag order. If (nz >= 0,
// the first nz zero entries are skipped over.
std::pair<int32, JpegError> Decoder::refineNonZeroes(JpegBlock *b, int32 zig, int32 zigEnd, int32 nz, int32 delta) {
    Decoder &d = *this;
	for (; zig <= zigEnd; zig++) {
        int u = unzig()[zig];
		if ((*b)[u] == 0) {
            if (nz == 0) {
				break;
			}
			nz--;
            continue;
		}
		uint8E bitErr = d.decodeBit();
		if (bitErr.second != JpegError::nil()) {
            return uint32E(0, bitErr.second);
		}
		if (!bitErr.first) {
			continue;
		}
		if ((*b)[u] >= 0) {
			(*b)[u] += delta;
		} else {
			(*b)[u] -= delta;
		}
	}
	return int32E(zig, JpegError::nil());
}
}


text:
$LOAD_PATH.unshift File.expand_path("../../lib", __FILE__)

require "bundler/setup"
require File.dirname(Gem::Specification.find_by_name("spring").loaded_from) + "/test/support/test"
require "minitest/autorun"

if defined?(Celluloid)
  require "celluloid/test"
  Celluloid.logger.level = Logger::WARN
end

Spring::Test.root = File.expand_path('..', __FILE__)

redpajama_set_name: RedPajamaGithub


text:
TRCKSMTHNG
==========

TRCKSMTHNG is a webtool based on HTML, CSS, Javascript and PHP to track time for something you want to track.

#WARNING
This tool is in an early Alpha stage and you should not use it in a production environment.

==========

TRCKSMTHNG is a small project by Kovah (www.Kovah.de)
Contributors: https://github.com/Kovah/TRCKSMTHNG/graphs/contributors


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Annls mycol. 37: 88 (1939)

#### Original name
Acanthostigma melanolasium Kirschst.

### Remarks
null


text:
<?php

namespace Template\LonelyBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class TemplateLonelyBundle extends Bundle
{
}


text:
<?php

namespace App\Badge\Infrastructure;

use App\Badge\Model\Image;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;

final class ResponseFactory
{
    /**
     * @throws \InvalidArgumentException
     */
    public static function createFromImage(Image $image, int $status, int $maxage = 3600, int $smaxage = 3600): Response
    {
        $response = new Response((string) $image, $status);

        $response->headers->set('Content-Type', 'image/svg+xml;charset=utf-8');
        $contentDisposition = $response->headers->makeDisposition(ResponseHeaderBag::DISPOSITION_INLINE, $image->getOutputFileName());
        $response->headers->set('Content-Disposition', $contentDisposition);

        $response->setMaxAge($maxage);
        $response->setSharedMaxAge($smaxage);
        $response->setPublic();

        return $response;
    }
}


text:
package com.silentmatt.dss;

import com.martiansoftware.jsap.FlaggedOption;
import com.martiansoftware.jsap.JSAP;
import com.martiansoftware.jsap.JSAPException;
import com.martiansoftware.jsap.ParseException;
import com.martiansoftware.jsap.StringParser;
import com.martiansoftware.jsap.Switch;
import com.martiansoftware.jsap.UnflaggedOption;
import com.martiansoftware.jsap.stringparsers.FileStringParser;
import com.martiansoftware.jsap.stringparsers.URLStringParser;
import java.io.File;
import java.io.PrintStream;
import java.net.MalformedURLException;

public class OptionsParser {
    private final JSAP jsap;

    public OptionsParser() {
        jsap = new JSAP();
        setupArguments();
    }

    public Configuration getConfiguration(String[] args) {
        return new JSAPConfiguration(jsap.parse(args));
    }

    public void printUsage(PrintStream out) {
        out.println("usage: java -jar dss.jar");
        out.println("       " + jsap.getUsage());
        out.println();
        out.println(jsap.getHelp());
    }

    private void setupArguments() {
        FlaggedOption outOpt = new FlaggedOption("out")
                .setStringParser(FileStringParser.getParser().setMustBeFile(true).setMustExist(false))
                .setRequired(false)
                .setAllowMultipleDeclarations(false)
                .setShortFlag('o');
        outOpt.setHelp("File to save outout to");

        Switch debugFlag = new Switch("debug")
                .setLongFlag("debug");
        debugFlag.setHelp("Don't remove DSS directives from output");

        Switch versionFlag = new Switch("version")
                .setShortFlag('v')
                .setLongFlag("version");
        versionFlag.setHelp("Show version information and exit");

        Switch testFlag = new Switch("test")
                .setShortFlag('t')
                .setLongFlag("test");
        testFlag.setHelp("Run tests in the specified directory");

        Switch colorFlag = new Switch("color")
                .setLongFlag("color");
        colorFlag.setHelp("Colorize test output");

        Switch compressFlag = new Switch("compress")
                .setShortFlag('c')
                .setLongFlag("compress");
        compressFlag.setHelp("Compress the CSS output.");

        Switch watchFlag = new Switch("watch")
                .setShortFlag('w')
                .setLongFlag("watch");
        watchFlag.setHelp("Re-process the file any time it changes.");

        Switch notifyFlag = new Switch("notify")
                .setShortFlag('n')
                .setLongFlag("notify");
        notifyFlag.setHelp("Pop-up a notification with notify-send when watched files are finished.");

        FlaggedOption defineOpt = new FlaggedOption("define")
                .setAllowMultipleDeclarations(true)
                .setRequired(false)
                .setShortFlag('d')
                .setLongFlag("define")
                .setUsageName("name:value")
                .setStringParser(JSAP.STRING_PARSER);
        defineOpt.setHelp("Pre-define a constant in the global namespace");

        UnflaggedOption urlOpt = new UnflaggedOption("url")
                .setStringParser(FileOrURLStringParser.getParser())
                .setRequired(true);
        urlOpt.setHelp("The filename or URL of the DSS file.");

        try {
            jsap.registerParameter(versionFlag);
            jsap.registerParameter(testFlag);
            jsap.registerParameter(colorFlag);
            jsap.registerParameter(debugFlag);
            jsap.registerParameter(compressFlag);
            jsap.registerParameter(watchFlag);
            jsap.registerParameter(notifyFlag);
            jsap.registerParameter(defineOpt);
            jsap.registerParameter(outOpt);

            jsap.registerParameter(urlOpt);
        } catch (JSAPException j) {
            throw new IllegalStateException("Unexpected Error: Illegal JSAP parameter.", j);
        }
    }

    private static class FileOrURLStringParser extends StringParser {
        private static final FileStringParser fileParser = FileStringParser.getParser();
        private static final URLStringParser urlParser = URLStringParser.getParser();

        private FileOrURLStringParser() {
            fileParser.setMustBeFile(false).setMustExist(true);
        }

        static FileOrURLStringParser getParser() {
            return new FileOrURLStringParser();
        }

        @Override
        public Object parse(String arg) throws ParseException {
            try {
                return urlParser.parse(arg);
            } catch (ParseException ex) {
                fileParser.setUp();
                File file = (File) fileParser.parse(arg);
                fileParser.tearDown();
                try {
                    return file.toURI().toURL();
                } catch (MalformedURLException ex1) {
                    throw new ParseException(ex1);
                }
            }
        }
    }
}


text:
namespace gl
{

Sampler::Sampler(rx::GLImplFactory *factory, SamplerID id)
    : RefCountObject(factory->generateSerial(), id),
      mState(),
      mDirty(true),
      mSampler(factory->createSampler(mState)),
      mLabel()
{}

Sampler::~Sampler()
{
    SafeDelete(mSampler);
}

void Sampler::onDestroy(const Context *context)
{
    if (mSampler)
    {
        mSampler->onDestroy(context);
    }
}

void Sampler::setLabel(const Context *context, const std::string &label)
{
    mLabel = label;
}

const std::string &Sampler::getLabel() const
{
    return mLabel;
}

void Sampler::setMinFilter(const Context *context, GLenum minFilter)
{
    mState.setMinFilter(minFilter);
    signalDirtyState();
}

GLenum Sampler::getMinFilter() const
{
    return mState.getMinFilter();
}

void Sampler::setMagFilter(const Context *context, GLenum magFilter)
{
    mState.setMagFilter(magFilter);
    signalDirtyState();
}

GLenum Sampler::getMagFilter() const
{
    return mState.getMagFilter();
}

void Sampler::setWrapS(const Context *context, GLenum wrapS)
{
    mState.setWrapS(wrapS);
    signalDirtyState();
}

GLenum Sampler::getWrapS() const
{
    return mState.getWrapS();
}

void Sampler::setWrapT(const Context *context, GLenum wrapT)
{
    mState.setWrapT(wrapT);
    signalDirtyState();
}

GLenum Sampler::getWrapT() const
{
    return mState.getWrapT();
}

void Sampler::setWrapR(const Context *context, GLenum wrapR)
{
    mState.setWrapR(wrapR);
    signalDirtyState();
}

GLenum Sampler::getWrapR() const
{
    return mState.getWrapR();
}

void Sampler::setMaxAnisotropy(const Context *context, float maxAnisotropy)
{
    mState.setMaxAnisotropy(maxAnisotropy);
    signalDirtyState();
}

float Sampler::getMaxAnisotropy() const
{
    return mState.getMaxAnisotropy();
}

void Sampler::setMinLod(const Context *context, GLfloat minLod)
{
    mState.setMinLod(minLod);
    signalDirtyState();
}

GLfloat Sampler::getMinLod() const
{
    return mState.getMinLod();
}

void Sampler::setMaxLod(const Context *context, GLfloat maxLod)
{
    mState.setMaxLod(maxLod);
    signalDirtyState();
}

GLfloat Sampler::getMaxLod() const
{
    return mState.getMaxLod();
}

void Sampler::setCompareMode(const Context *context, GLenum compareMode)
{
    mState.setCompareMode(compareMode);
    signalDirtyState();
}

GLenum Sampler::getCompareMode() const
{
    return mState.getCompareMode();
}

void Sampler::setCompareFunc(const Context *context, GLenum compareFunc)
{
    mState.setCompareFunc(compareFunc);
    signalDirtyState();
}

GLenum Sampler::getCompareFunc() const
{
    return mState.getCompareFunc();
}

void Sampler::setSRGBDecode(const Context *context, GLenum sRGBDecode)
{
    mState.setSRGBDecode(sRGBDecode);
    signalDirtyState();
}

GLenum Sampler::getSRGBDecode() const
{
    return mState.getSRGBDecode();
}

void Sampler::setBorderColor(const Context *context, const ColorGeneric &color)
{
    mState.setBorderColor(color);
    signalDirtyState();
}

const ColorGeneric &Sampler::getBorderColor() const
{
    return mState.getBorderColor();
}

const SamplerState &Sampler::getSamplerState() const
{
    return mState;
}

rx::SamplerImpl *Sampler::getImplementation() const
{
    return mSampler;
}

angle::Result Sampler::syncState(const Context *context)
{
    ASSERT(isDirty());
    angle::Result result = mSampler->syncState(context, mDirty);
    mDirty               = result != angle::Result::Continue;
    return result;
}

void Sampler::signalDirtyState()
{
    mDirty = true;
    onStateChange(angle::SubjectMessage::DirtyBitsFlagged);
}

}  // namespace gl


text:
// Tencent is pleased to support the open source community by making RapidJSON available.
//
// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip.
//
// Licensed under the MIT License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// http://opensource.org/licenses/MIT
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.

#ifndef RAPIDJSON_ERROR_EN_H_
#define RAPIDJSON_ERROR_EN_H_

#include "error.h"

#ifdef __clang__
RAPIDJSON_DIAG_PUSH
RAPIDJSON_DIAG_OFF(switch-enum)
RAPIDJSON_DIAG_OFF(covered-switch-default)
#endif

RAPIDJSON_NAMESPACE_BEGIN

//! Maps error code of parsing into error message.
/*!
    \ingroup RAPIDJSON_ERRORS
    \param parseErrorCode Error code obtained in parsing.
    \return the error message.
    \note User can make a copy of this function for localization.
        Using switch-case is safer for future modification of error codes.
*/
inline const RAPIDJSON_ERROR_CHARTYPE* GetParseError_En(ParseErrorCode parseErrorCode) {
    switch (parseErrorCode) {
        case kParseErrorNone:                           return RAPIDJSON_ERROR_STRING("No error.");

        case kParseErrorDocumentEmpty:                  return RAPIDJSON_ERROR_STRING("The document is empty.");
        case kParseErrorDocumentRootNotSingular:        return RAPIDJSON_ERROR_STRING("The document root must not be followed by other values.");

        case kParseErrorValueInvalid:                   return RAPIDJSON_ERROR_STRING("Invalid value.");

        case kParseErrorObjectMissName:                 return RAPIDJSON_ERROR_STRING("Missing a name for object member.");
        case kParseErrorObjectMissColon:                return RAPIDJSON_ERROR_STRING("Missing a colon after a name of object member.");
        case kParseErrorObjectMissCommaOrCurlyBracket:  return RAPIDJSON_ERROR_STRING("Missing a comma or '}' after an object member.");

        case kParseErrorArrayMissCommaOrSquareBracket:  return RAPIDJSON_ERROR_STRING("Missing a comma or ']' after an array element.");

        case kParseErrorStringUnicodeEscapeInvalidHex:  return RAPIDJSON_ERROR_STRING("Incorrect hex digit after \\u escape in string.");
        case kParseErrorStringUnicodeSurrogateInvalid:  return RAPIDJSON_ERROR_STRING("The surrogate pair in string is invalid.");
        case kParseErrorStringEscapeInvalid:            return RAPIDJSON_ERROR_STRING("Invalid escape character in string.");
        case kParseErrorStringMissQuotationMark:        return RAPIDJSON_ERROR_STRING("Missing a closing quotation mark in string.");
        case kParseErrorStringInvalidEncoding:          return RAPIDJSON_ERROR_STRING("Invalid encoding in string.");

        case kParseErrorNumberTooBig:                   return RAPIDJSON_ERROR_STRING("Number too big to be stored in double.");
        case kParseErrorNumberMissFraction:             return RAPIDJSON_ERROR_STRING("Miss fraction part in number.");
        case kParseErrorNumberMissExponent:             return RAPIDJSON_ERROR_STRING("Miss exponent in number.");

        case kParseErrorTermination:                    return RAPIDJSON_ERROR_STRING("Terminate parsing due to Handler error.");
        case kParseErrorUnspecificSyntaxError:          return RAPIDJSON_ERROR_STRING("Unspecific syntax error.");

        default:                                        return RAPIDJSON_ERROR_STRING("Unknown error.");
    }
}

//! Maps error code of validation into error message.
/*!
    \ingroup RAPIDJSON_ERRORS
    \param validateErrorCode Error code obtained from validator.
    \return the error message.
    \note User can make a copy of this function for localization.
        Using switch-case is safer for future modification of error codes.
*/
inline const RAPIDJSON_ERROR_CHARTYPE* GetValidateError_En(ValidateErrorCode validateErrorCode) {
    switch (validateErrorCode) {
        case kValidateErrors:                           return RAPIDJSON_ERROR_STRING("One or more validation errors have occurred");
        case kValidateErrorNone:                        return RAPIDJSON_ERROR_STRING("No error.");

        case kValidateErrorMultipleOf:                  return RAPIDJSON_ERROR_STRING("Number '%actual' is not a multiple of the 'multipleOf' value '%expected'.");
        case kValidateErrorMaximum:                     return RAPIDJSON_ERROR_STRING("Number '%actual' is greater than the 'maximum' value '%expected'.");
        case kValidateErrorExclusiveMaximum:            return RAPIDJSON_ERROR_STRING("Number '%actual' is greater than or equal to the 'exclusiveMaximum' value '%expected'.");
        case kValidateErrorMinimum:                     return RAPIDJSON_ERROR_STRING("Number '%actual' is less than the 'minimum' value '%expected'.");
        case kValidateErrorExclusiveMinimum:            return RAPIDJSON_ERROR_STRING("Number '%actual' is less than or equal to the 'exclusiveMinimum' value '%expected'.");

        case kValidateErrorMaxLength:                   return RAPIDJSON_ERROR_STRING("String '%actual' is longer than the 'maxLength' value '%expected'.");
        case kValidateErrorMinLength:                   return RAPIDJSON_ERROR_STRING("String '%actual' is shorter than the 'minLength' value '%expected'.");
        case kValidateErrorPattern:                     return RAPIDJSON_ERROR_STRING("String '%actual' does not match the 'pattern' regular expression.");

        case kValidateErrorMaxItems:                    return RAPIDJSON_ERROR_STRING("Array of length '%actual' is longer than the 'maxItems' value '%expected'.");
        case kValidateErrorMinItems:                    return RAPIDJSON_ERROR_STRING("Array of length '%actual' is shorter than the 'minItems' value '%expected'.");
        case kValidateErrorUniqueItems:                 return RAPIDJSON_ERROR_STRING("Array has duplicate items at indices '%duplicates' but 'uniqueItems' is true.");
        case kValidateErrorAdditionalItems:             return RAPIDJSON_ERROR_STRING("Array has an additional item at index '%disallowed' that is not allowed by the schema.");

        case kValidateErrorMaxProperties:               return RAPIDJSON_ERROR_STRING("Object has '%actual' members which is more than 'maxProperties' value '%expected'.");
        case kValidateErrorMinProperties:               return RAPIDJSON_ERROR_STRING("Object has '%actual' members which is less than 'minProperties' value '%expected'.");
        case kValidateErrorRequired:                    return RAPIDJSON_ERROR_STRING("Object is missing the following members required by the schema: '%missing'.");
        case kValidateErrorAdditionalProperties:        return RAPIDJSON_ERROR_STRING("Object has an additional member '%disallowed' that is not allowed by the schema.");
        case kValidateErrorPatternProperties:           return RAPIDJSON_ERROR_STRING("Object has 'patternProperties' that are not allowed by the schema.");
        case kValidateErrorDependencies:                return RAPIDJSON_ERROR_STRING("Object has missing property or schema dependencies, refer to following errors.");

        case kValidateErrorEnum:                        return RAPIDJSON_ERROR_STRING("Property has a value that is not one of its allowed enumerated values.");
        case kValidateErrorType:                        return RAPIDJSON_ERROR_STRING("Property has a type '%actual' that is not in the following list: '%expected'.");

        case kValidateErrorOneOf:                       return RAPIDJSON_ERROR_STRING("Property did not match any of the sub-schemas specified by 'oneOf', refer to following errors.");
        case kValidateErrorOneOfMatch:                  return RAPIDJSON_ERROR_STRING("Property matched more than one of the sub-schemas specified by 'oneOf'.");
        case kValidateErrorAllOf:                       return RAPIDJSON_ERROR_STRING("Property did not match all of the sub-schemas specified by 'allOf', refer to following errors.");
        case kValidateErrorAnyOf:                       return RAPIDJSON_ERROR_STRING("Property did not match any of the sub-schemas specified by 'anyOf', refer to following errors.");
        case kValidateErrorNot:                         return RAPIDJSON_ERROR_STRING("Property matched the sub-schema specified by 'not'.");

        default:                                        return RAPIDJSON_ERROR_STRING("Unknown error.");
    }
}

RAPIDJSON_NAMESPACE_END

#ifdef __clang__
RAPIDJSON_DIAG_POP
#endif

#endif // RAPIDJSON_ERROR_EN_H_


text:
using System;
using System.Collections.Generic;
using System.Text;
using Serializer.Protobuf_net;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Diagnostics;
using Serializer.Binaryformatter;
using Serializer.Binaryformatter.customFormatter;
using ProtoBuf;
using Serializer.Binaryformatter.protobuff;

namespace Serializer
{

    /// <summary>
    /// Way to run testing different implmentations of serilzation and de deserlization!
    ///
    /// Test to be performed is with person tracking data serlization and de serilazation.
    ///
    /// simple Binary formatter
    ///
    /// custom Binary formatter
    ///
    /// protobuf-net by marc.gravell 10 times faster than binary formatter
    ///
    /// write my own with BinaryWriter
    ///
    /// Expectations
    /// from simple binary formatter to a custom formatter we should excpet a 10 to 15 times increase in spead
    ///
    /// and from binaryformatter  to proto buf  3-5 times better time characteristics than BinaryFormatter, and worse time characteristics than Manual approach.
    ///
    /// source is this: http://www.codeproject.com/Articles/311944/BinaryFormatter-or-Manual-serializing
    /// http://maxondev.com/serialization-performance-comparison-c-net-formats-frameworks-xmldatacontractserializer-xmlserializer-binaryformatter-json-newtonsoft-servicestack-text/
    /// </summary>
    class Program
    {
        static void Main(string[] args)
        {

            Person per = new Person();

            //test basic binary formatter
            basicBinaryFormatter();

            customBinaryFormatter();

            protobuffFormatterTest();

            //temp test

            Console.ReadLine();

        }

        private static void modtes(test tes)
        {
            tes.x++;
        }

        public class test
        {
            public int x = 0;

        }

        private static void protobuffFormatterTest()
        {

            pPerson per = new pPerson();
            pPerson per2;
            MemoryStream mem = new MemoryStream(10000);
            //

            ProtoBuf.Serializer.PrepareSerializer<pPerson>();

            Stopwatch st = new Stopwatch();
            Stopwatch st1 = new Stopwatch();
            Stopwatch st2 = new Stopwatch();

            st.Start();

            st1.Start();
            for (int i = 0; i < 1000; i++)
            {
                mem.Position = 0;
                ProtoBuf.Serializer.Serialize(mem, per);

            }
            st1.Stop();

            st2.Start();
            for (int i = 0; i < 1000; i++)
            {
                //seralize
                //deseralize
                mem.Position = 0;
                per2 =  ProtoBuf.Serializer.Deserialize<pPerson>(mem);

            }
            st2.Stop();
            st.Stop();

            decimal serialzeTime = calcElapsedTime(st1.ElapsedMilliseconds);
            decimal deserialzeTime = calcElapsedTime(st2.ElapsedMilliseconds);
            decimal totserialzeTime = calcElapsedTime(st.ElapsedMilliseconds);
            Console.WriteLine("protobuf serialiazer : {0} ms per iteration", serialzeTime);
            Console.WriteLine("protobuf deserialiazer : {0} ms per iteration", deserialzeTime);
            Console.WriteLine("protobuf rtt serlize time : {0} ms per iteration", totserialzeTime);

            mem.Close();

        }

        private static void customBinaryFormatter()
        {

            cPerson per = new cPerson();
            cPerson per2;

            BinaryFormatter formatter = new BinaryFormatter();
            MemoryStream mem = new MemoryStream(10000);

            // seralize and deseralize thousand body objects
            Stopwatch st = new Stopwatch();
            Stopwatch st1 = new Stopwatch();
            Stopwatch st2 = new Stopwatch();

            st.Start();

            st1.Start();
            for (int i = 0; i < 1000; i++)
            {
                mem.Position = 0;
                formatter.Serialize(mem, per);
            }
            st1.Stop();

            st2.Start();
            for (int i = 0; i < 1000; i++)
            {
                //seralize
                //deseralize
                mem.Position = 0;
                per2 = (cPerson)formatter.Deserialize(mem);

            }
            st2.Stop();
            st.Stop();

            decimal serialzeTime = calcElapsedTime(st1.ElapsedMilliseconds);
            decimal deserialzeTime = calcElapsedTime(st2.ElapsedMilliseconds);
            decimal totserialzeTime = calcElapsedTime(st.ElapsedMilliseconds);
            Console.WriteLine("Custom binary formatter serialiazer : {0} ms per iteration", serialzeTime);
            Console.WriteLine("Custom binary formatter deserialiazer : {0} ms per iteration", deserialzeTime);
            Console.WriteLine("Custom binary formatter rtt serlize time : {0} ms per iteration", totserialzeTime);

            mem.Close();
        }

        /// <summary>
        /// Basic binary formamtter takes 0.336 ms per iteration on i7 4660k 4.36 GHz
        /// my computer is on 3.9 ghz
        /// A57 - 2.1GHz
        /// A53 - 1.5GHz
        ///
        /// the vr headset is clocked around  1.2 - 1.5 GHz
        ///
        /// 4.4 Ghz
        ///
        /// </summary>
        /// <returns>
        /// output:
        /// Basic binary formatter serialiazer : 0.177 ms per iteration
        /// Basic binary formatter deserialiazer : 0.177 ms per iteration
        /// Basic binary formatter rtt serlize time : 0.354 ms per iteration
        /// </returns>

        private static void basicBinaryFormatter()
        {

            bPerson pers = new bPerson();

            BinaryFormatter formatter = new BinaryFormatter();
            MemoryStream mem = new MemoryStream(10000);
            bPerson pers2;

            // seralize and deseralize thousand body objects
            Stopwatch st = new Stopwatch();
            Stopwatch st1 = new Stopwatch();
            Stopwatch st2 = new Stopwatch();

            st.Start();

            st1.Start();
            for (int i = 0; i < 1000; i++)
            {
                mem.Position = 0;
                formatter.Serialize(mem, pers);
            }
            st1.Stop();

            st2.Start();
            for (int i = 0; i < 1000; i++)
            {
                //seralize
                //deseralize
                mem.Position = 0;
                pers2 = (bPerson)formatter.Deserialize(mem);

            }
            st2.Stop();
            st.Stop();

            decimal serialzeTime = calcElapsedTime(st1.ElapsedMilliseconds);
            decimal deserialzeTime = calcElapsedTime(st2.ElapsedMilliseconds);
            decimal totserialzeTime = calcElapsedTime(st.ElapsedMilliseconds);
            Console.WriteLine("Basic binary formatter serialiazer : {0} ms per iteration", serialzeTime);
            Console.WriteLine("Basic binary formatter deserialiazer : {0} ms per iteration", deserialzeTime);
            Console.WriteLine("Basic binary formatter rtt serlize time : {0} ms per iteration", totserialzeTime);

            mem.Close();
        }

        private static decimal calcElapsedTime(long ElapsedMilliseconds)
        {
            return Convert.ToDecimal(ElapsedMilliseconds) / Convert.ToDecimal(1000);
        }

    }
}


text:
/**
 * About dialog.
 */
package com.dmdirc.addons.ui_swing.dialogs.about;


text:
var Style = require('..');
var assert = require('assert');

describe('Styl', function(){
  describe('.use()', function(){
    it('should work', function(done){
      var style = new Style('body { color: blue }');

      style.use(function(style){
        assert(style);
        done();
      });
    })
  })
})


text:
<?php

namespace Alpixel\Bundle\CMSBundle\Admin;

use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Route\RouteCollection;

class AdminBlock extends BaseBlockEntityAdmin
{
    protected $baseRouteName = 'alpixel_admin_cms_block';
    protected $baseRoutePattern = 'block';

    protected $datagridValues = [
        '_page'       => 1,
        '_sort_order' => 'DESC',
        '_sort_by'    => 'dateUpdated',
    ];

    protected function configureRoutes(RouteCollection $collection)
    {
        $collection->clearExcept(['list', 'edit']);
    }

    /**
     * @param \Sonata\AdminBundle\Datagrid\ListMapper $listMapper
     *
     * @return void
     */
    protected function configureListFields(ListMapper $listMapper)
    {
        $listMapper
            ->add('id')
            ->add('locale', null, [
                'label' => 'Langue',
            ])
            ->add('name', null, [
                'label' => 'Nom',
            ])
            ->add('dateCreated', null, [
                'label' => 'Date de création',
            ])
            ->add('dateUpdated', null, [
                'label' => 'Date d\'édition',
            ])
            ->add('_action', 'actions', [
                'actions' => [
                    'edit' => ['template' => 'AlpixelCMSBundle:admin:fields/list__block_action_edit.html.twig'],
                ],
            ]);
    }
}


text:
package com.gs.obevo.db.impl.core.jdbc;

import javax.sql.DataSource;

import com.gs.obevo.db.api.appdata.DbEnvironment;
import com.gs.obevo.util.inputreader.Credential;

/**
 * DataSourceFactory that will switch between an LDAP-lookup based implementation and a JDBC URL based implementation
 * depending on the parameters passed in (specifying {@link DbEnvironment#dbDataSourceName} will cause the LDAP-lookup
 * factory to be used.
 */
public class CompositeDataSourceFactory implements DataSourceFactory {
    private final DataSourceFactory dsLookupDataSourceFactory;
    private final DataSourceFactory jdbcUrlDataSourceFactory;

    public CompositeDataSourceFactory(DataSourceFactory dsLookupDataSourceFactory, DataSourceFactory jdbcUrlDataSourceFactory) {
        this.dsLookupDataSourceFactory = dsLookupDataSourceFactory;
        this.jdbcUrlDataSourceFactory = jdbcUrlDataSourceFactory;
    }

    @Override
    public DataSource createDataSource(DbEnvironment env, Credential credential, int numThreads) {
        if (env.getDbDataSourceName() != null) {
            return this.dsLookupDataSourceFactory.createDataSource(env, credential, numThreads);
        }

        return this.jdbcUrlDataSourceFactory.createDataSource(env, credential, numThreads);
    }
}


text:
module CdfTable

  def default_poa_columns(t)
    t.string :record_code, :limit => 2
    t.string :sequence_number, :limit => 5
    t.string :po_number, :limit => 22
    t.timestamps
  end

  def default_inv_columns(t)
    t.string :record_code, :limit => 2
    t.string :sequence, :limit => 5
    t.integer :invoice_number
    t.timestamps
    t.references :cdf_invoice_file
  end
end


text:
package me.rafaskb.ticketmaster.commands;

import org.bukkit.command.CommandSender;

import me.rafaskb.ticketmaster.models.TicketComment;
import me.rafaskb.ticketmaster.models.TicketPriority;
import me.rafaskb.ticketmaster.models.TicketStatus;
import me.rafaskb.ticketmaster.sql.Controller;
import me.rafaskb.ticketmaster.utils.Lang;
import me.rafaskb.ticketmaster.utils.LangMacro;
import me.rafaskb.ticketmaster.utils.Perm;
import me.rafaskb.ticketmaster.utils.TicketActionBuilder;
import me.rafaskb.ticketmaster.utils.TicketLogBuilder;
import me.rafaskb.ticketmaster.utils.Utils;

public class CommandClaim extends Command {
	private static final int INDEX_ID = 1;

	public CommandClaim() {
		super(Perm.PRIORITY_LOW);
	}

	@Override
	protected void run(CommandSender sender, String[] args) {
		// If not enough arguments
		if(args.length != 2) {
			Lang.sendErrorMessage(sender, Lang.CLAIM_COMMAND_USAGE);
			return;
		}
		// If can't parse ID argument as integer
		int id = 0;
		try {
			id = Integer.parseInt(args[INDEX_ID]);
		} catch (NumberFormatException e) {
			Lang.sendErrorMessage(sender, Lang.CLAIM_COMMAND_USAGE);
			return;
		}

		// If ID not found, show 'ticket_not_found' error (replace <id>)
		if(!Controller.ticketExists(id)) {
			Lang.sendTicketNotFoundMessage(sender, id);
			return;
		}

		// Get ticket priority and check if sender can manage it
		TicketPriority priority = Controller.getTicketPriority(id);
		if(!Perm.check(sender, priority.getRequiredPermission())) {
			Lang.sendErrorMessage(sender, Lang.TICKET_MANAGEMENT_NO_PERMS);
			return;
		}

		// If ticket is closed
		TicketStatus status = Controller.getTicketStatus(id);
		if(status == TicketStatus.CLOSED) {
			Lang.sendErrorMessage(sender, Lang.CLAIM_COMMAND_CLOSED);
			return;
		}

		// Change status
		boolean success = Controller.setTicketStatus(id, TicketStatus.CLAIMED)
			& Controller.setTicketAssignee(id, sender.getName());

		// Success
		if(success) {
			// Add log to ticket as a comment
			TicketComment log = new TicketComment(id, sender.getName(), TicketLogBuilder.claimed());
			Controller.pushTicketComment(log);

			// Message command sender
			String msg = LangMacro.replaceId(Lang.CLAIM_COMMAND_SUCCESS, id);
			Lang.sendMessage(sender, msg);

			// Message ticket submitter
			String actionMessage = TicketActionBuilder.claimed(sender.getName(), id);
			String ticketSubmitter = Controller.getTicketSubmitter(id);
			if(!Utils.sendActionMessage(ticketSubmitter, actionMessage))
			     Controller.insertPendingMessage(ticketSubmitter, actionMessage);

			return;
		}

		// Failure
		else {
			String msg = LangMacro.replaceId(Lang.CLAIM_COMMAND_FAILURE, id);
			Lang.sendErrorMessage(sender, msg);
			return;
		}
	}

}


text:
{{--
    List of the accepted parameters
    $deliveries             Required        The list of Delivery
    $deliveries_pagination  Default:0       The number of Delivery displayed on the page. 0 means we use the default value
    [$allow_delivery_view]  Default: false  Allow navigating to the Delivery
--}}
@php($deliveries_pagination = (isset($deliveries_pagination))?$deliveries_pagination:0)
@php($allow_delivery_view = (isset($allow_delivery_view))?$allow_delivery_view:false)

{{-- Display a Splash message when there are no results in the search --}}
@if($deliveries->paginate($deliveries_pagination)->count() == 0)
    @include('layout.components.view.no_result')
@else

                @lang('livror.labels.date')
                @lang('livror.labels.deliveries.delivery')
                @lang('livror.labels.total_without_taxes')

        @foreach ($deliveries->paginate($deliveries_pagination) as $delivery)

            @component('layout.components.view.date') @slot('date') {{$delivery->updated_at}} @endslot @endcomponent

                @if($allow_delivery_view)
                    id}} d-print-none" href="{{route('deliverySummary', ['delivery' => $delivery->id])}}">{{$delivery->visual_id}}
                    id}} d-none d-print-block">{{$delivery->visual_id}}
                @else
                    {{$delivery->visual_id}}
                @endif

            @money($delivery->total, 'EUR')

        @endforeach

@endif

@lang('livror.labels.total_without_taxes')

@money($bill->total, 'EUR')

@lang('livror.labels.vat') {{$bill->taxes}}%

@money(($bill->taxed_total - $bill->total), 'EUR')

@lang('livror.labels.total_with_taxes')

@money($bill->taxed_total, 'EUR')


text:
<?php
namespace Flex\Code\Html\TagGenerator\Entity;

/**
 * Class Tag
 *
 * @author Jeff Tunessen <jeff.tunessen@gmail.com>
 */
class Tag
{
    /**
     * @var int
     */
    private $id;

    /**
     * @var string
     */
    private $name;

    /**
     * @var string
     */
    private $link;

    /**
     * @var string
     */
    private $shortDescription;

    /**
     * @var string
     */
    private $longDescription;

    /**
     * @var bool
     */
    private $isVoid;

    /**
     * @var bool
     */
    private $isGlobalAttributeAware;

    /**
     * @var bool
     */
    private $isClipboardEventAware;

    /**
     * @var bool
     */
    private $isFormEventAware;

    /**
     * @var bool
     */
    private $isKeyboardEventAware;

    /**
     * @var bool
     */
    private $isMediaEventAware;

    /**
     * @var bool
     */
    private $isMiscEventAware;

    /**
     * @var bool
     */
    private $isMouseEventAware;

    /**
     * @var bool
     */
    private $isWindowEventAware;

    /**
     * @var AttributeCollection
     */
    private $attributes;

    /**
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @param int $id
     */
    public function setId($id)
    {
        $this->id = $id;
    }

    /**
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * @param string $name
     */
    public function setName($name)
    {
        $this->name = $name;
    }

    /**
     * @return string
     */
    public function getLink()
    {
        return $this->link;
    }

    /**
     * @param string $link
     */
    public function setLink($link)
    {
        $this->link = $link;
    }

    /**
     * @return string
     */
    public function getShortDescription()
    {
        return $this->shortDescription;
    }

    /**
     * @param string $shortDescription
     */
    public function setShortDescription($shortDescription)
    {
        $this->shortDescription = $shortDescription;
    }

    /**
     * @return string
     */
    public function getLongDescription()
    {
        return $this->longDescription;
    }

    /**
     * @param string $longDescription
     */
    public function setLongDescription($longDescription)
    {
        $this->longDescription = $longDescription;
    }

    /**
     * @return boolean
     */
    public function isVoid()
    {
        return $this->isVoid;
    }

    /**
     * @param boolean $isVoid
     */
    public function setIsVoid($isVoid)
    {
        $this->isVoid = $isVoid;
    }

    /**
     * @return boolean
     */
    public function isGlobalAttributeAware()
    {
        return $this->isGlobalAttributeAware;
    }

    /**
     * @param boolean $isGlobalAttributeAware
     */
    public function setIsGlobalAttributeAware($isGlobalAttributeAware)
    {
        $this->isGlobalAttributeAware = $isGlobalAttributeAware;
    }

    /**
     * @return boolean
     */
    public function isClipboardEventAware()
    {
        return $this->isClipboardEventAware;
    }

    /**
     * @param boolean $isClipboardEventAware
     */
    public function setIsClipboardEventAware($isClipboardEventAware)
    {
        $this->isClipboardEventAware = $isClipboardEventAware;
    }

    /**
     * @return boolean
     */
    public function isFormEventAware()
    {
        return $this->isFormEventAware;
    }

    /**
     * @param boolean $isFormEventAware
     */
    public function setIsFormEventAware($isFormEventAware)
    {
        $this->isFormEventAware = $isFormEventAware;
    }

    /**
     * @return boolean
     */
    public function isKeyboardEventAware()
    {
        return $this->isKeyboardEventAware;
    }

    /**
     * @param boolean $isKeyboardEventAware
     */
    public function setIsKeyboardEventAware($isKeyboardEventAware)
    {
        $this->isKeyboardEventAware = $isKeyboardEventAware;
    }

    /**
     * @return boolean
     */
    public function isMediaEventAware()
    {
        return $this->isMediaEventAware;
    }

    /**
     * @param boolean $isMediaEventAware
     */
    public function setIsMediaEventAware($isMediaEventAware)
    {
        $this->isMediaEventAware = $isMediaEventAware;
    }

    /**
     * @return boolean
     */
    public function isMiscEventAware()
    {
        return $this->isMiscEventAware;
    }

    /**
     * @param boolean $isMiscEventAware
     */
    public function setIsMiscEventAware($isMiscEventAware)
    {
        $this->isMiscEventAware = $isMiscEventAware;
    }

    /**
     * @return boolean
     */
    public function isMouseEventAware()
    {
        return $this->isMouseEventAware;
    }

    /**
     * @param boolean $isMouseEventAware
     */
    public function setIsMouseEventAware($isMouseEventAware)
    {
        $this->isMouseEventAware = $isMouseEventAware;
    }

    /**
     * @return boolean
     */
    public function isWindowEventAware()
    {
        return $this->isWindowEventAware;
    }

    /**
     * @param boolean $isWindowEventAware
     */
    public function setIsWindowEventAware($isWindowEventAware)
    {
        $this->isWindowEventAware = $isWindowEventAware;
    }

    /**
     * @return AttributeCollection
     */
    public function getAttributes()
    {
        return $this->attributes;
    }

    /**
     * @param AttributeCollection $attributes
     */
    public function setAttributes(AttributeCollection $attributes)
    {
        $this->attributes = $attributes;
    }
}


text:
/* eslint-env jest */
import { groupStore as store } from '../group-store'
import fs from 'file-system'
process.env.GROUPS_PATH = './.groups.test.store.json'

function deleteFile () {
  if (fs.existsSync(process.env.GROUPS_PATH)) {
    fs.unlinkSync(process.env.GROUPS_PATH)
  }
}

describe('crud', () => {
  beforeEach(() => {
    deleteFile()
    store.save({ name: 'some group', accessRules: { 'someService': [{ asset: '*', role: '*' }] } })
    store.save({ name: 'some other group', accessRules: { 'a different service': [{ asset: 'a', role: 'b' }] } })
  })

  test('it has a default employee group', () => {
    const employeeGroup = store.get('Employees')
    expect(employeeGroup).not.toBeNull()
  })

  test('get(groupName)', () => {
    let retrieved = store.get('some group')

    expect(retrieved.name).toBe('some group')
    expect(retrieved.accessRules).toEqual({ 'someService': [{ asset: '*', role: '*' }] })
  })

  test('getAll()', () => {
    let retrieved = store.getAll()

    expect(retrieved.length).toBe(3)
    expect(retrieved).toEqual([
      { name: 'Employees', accessRules: {} },
      { name: 'some group', accessRules: { 'someService': [{ asset: '*', role: '*' }] } },
      { name: 'some other group', accessRules: { 'a different service': [{ asset: 'a', role: 'b' }] } }
    ])
  })

  test('getAccessRules(groupName, serviceId)', () => {
    let accessRules = store.getAccessRules('some group', 'someService')

    expect(accessRules).toEqual([{ asset: '*', role: '*' }])
  })

  test('exists(groupName)', () => {
    expect(store.exists('some group')).toBe(true)
    expect(store.exists('unknown group')).toBe(false)
  })

  test('save(group)', () => {
    store.save({ name: 'some group', accessRules: {} })
    let retrieved = store.get('some group')

    expect(retrieved).toEqual({ name: 'some group', accessRules: {} })
  })

  test('delete(groupName)', () => {
    store.delete('some group')
    let retrieved = store.get('some group')

    expect(retrieved).toBeNull()
  })
})


text:
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Runtime.Serialization;
using Microsoft.AspNet.WebHooks.Properties;

namespace Microsoft.AspNet.WebHooks
{
    /// <summary>
    /// Contains WebHook settings that are provided by the outside, for example through application settings.
    /// </summary>
    [SuppressMessage("Microsoft.Usage", "CA2240:ImplementISerializableCorrectly", Justification = "This class is not intended for XML serialization")]
    [Serializable]
    public class NotificationDictionary : Dictionary<string, object>
    {
        internal const string ActionKey = "Action";

        /// <summary>
        /// Initializes a new empty <see cref="NotificationDictionary"/>.
        /// </summary>
        public NotificationDictionary()
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="NotificationDictionary"/> class.
        /// </summary>
        /// <param name="action">An action describing the notification. In order for the actions to match
        /// the WebHook filter, it must match one or more of the filter values registered with the
        /// <see cref="IWebHookFilterManager"/>.</param>
        /// <param name="data">Optional additional data to include in the WebHook request.</param>
        public NotificationDictionary(string action, object data)
        {
            if (action == null)
            {
                throw new ArgumentNullException(nameof(action));
            }

            this[ActionKey] = action;
            IDictionary<string, object> dataAsDictionary = data as IDictionary<string, object>;
            if (dataAsDictionary == null && data != null)
            {
                dataAsDictionary = new Dictionary<string, object>();
                PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(data);
                foreach (PropertyDescriptor prop in properties)
                {
                    object val = prop.GetValue(data);
                    dataAsDictionary.Add(prop.Name, val);
                }
            }

            if (dataAsDictionary != null)
            {
                foreach (KeyValuePair<string, object> item in dataAsDictionary)
                {
                    this[item.Key] = item.Value;
                }
            }
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="NotificationDictionary"/> class with the specified serialization information and streaming context.
        /// </summary>
        /// <param name="info">A <see cref="SerializationInfo"/> containing information about the <see cref="NotificationDictionary"/> to be initialized.</param>
        /// <param name="context">A <see cref="StreamingContext"/> that indicates the source destination and context information of a serialized stream.</param>
        protected NotificationDictionary(SerializationInfo info, StreamingContext context)
            : base(info, context)
        {
        }

        /// <summary>
        /// Gets or sets the Action for this instance.
        /// </summary>
        public string Action
        {
            get
            {
                return this.GetValueOrDefault<string>(ActionKey);
            }
            set
            {
                if (value == null)
                {
                    throw new ArgumentNullException(nameof(value));
                }
                this[ActionKey] = value;
            }
        }

        /// <summary>
        /// Gets or sets the value associated with the specified key.
        /// </summary>
        /// <param name="key">The key of the value to get or set.</param>
        /// <returns>The value associated with the specified key. If the specified key is not found, a get operation throws a <see cref="KeyNotFoundException"/>, and a set operation creates a new element with the specified key.</returns>
        public new object this[string key]
        {
            get
            {
                try
                {
                    return base[key];
                }
                catch (KeyNotFoundException)
                {
                    string msg = string.Format(CultureInfo.CurrentCulture, CustomResources.Notification_KeyNotFound, key);
                    throw new KeyNotFoundException(msg);
                }
            }

            set
            {
                base[key] = value;
            }
        }
    }
}


text:
package com.tc.di.guicer;

import com.google.inject.Injector;

@SuppressWarnings("rawtypes")
public interface IGuicer {

	public abstract Injector getInjector();

	public <T> T createObject(Class cls);

	public abstract <T> T createObject(Class cls, String name);

	public abstract <T> T createObject( Class cls, String name, boolean inject);

	public abstract void inject(Object o);

	public abstract String getPluginId();

}


text:
import PyPDF2
import struct


text:
<?php

namespace Lexik\Bundle\JWTAuthenticationBundle\Tests\Functional;

use Psr\Log\NullLogger;
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Kernel;

/**
 * AppKernel.
 */
class AppKernel extends Kernel
{
    private $encoder;
    private $userProvider;

    public function __construct($environment, $debug)
    {
        parent::__construct($environment, $debug);

        $this->encoder      = getenv('ENCODER') ?: 'default';
        $this->userProvider = getenv('PROVIDER') ?: 'in_memory';
    }

    /**
     * {@inheritdoc}
     */
    public function registerBundles()
    {
        return [
            new \Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
            new \Symfony\Bundle\SecurityBundle\SecurityBundle(),
            new \Lexik\Bundle\JWTAuthenticationBundle\LexikJWTAuthenticationBundle(),
            new \Lexik\Bundle\JWTAuthenticationBundle\Tests\Functional\Bundle\Bundle(),
        ];
    }

    public function getRootDir()
    {
        return __DIR__;
    }

    /**
     * {@inheritdoc}
     */
    public function getCacheDir()
    {
        return sys_get_temp_dir().'/LexikJWTAuthenticationBundle/cache';
    }

    /**
     * {@inheritdoc}
     */
    public function getLogDir()
    {
        return sys_get_temp_dir().'/LexikJWTAuthenticationBundle/logs';
    }

    /**
     * {@inheritdoc}
     */
    public function registerContainerConfiguration(LoaderInterface $loader)
    {
        $loader->load(__DIR__.sprintf('/config/config_%s.yml', $this->encoder));
        $loader->load(__DIR__.sprintf('/config/security_%s.yml', $this->userProvider));
    }

    public function getUserProvider()
    {
        return $this->userProvider;
    }

    public function getEncoder()
    {
        return $this->encoder;
    }

    protected function build(ContainerBuilder $container)
    {
        $container->register('logger', NullLogger::class);
    }
}


text:
{{if self_registration:}}
{{login_form[0][-1][1].append(A(T("Register for Account"), _href=URL(f="user", args="register"), _id="register-btn", _class="action-lnk"))}}
{{pass}}
{{login_form[0][-1][1].append(A(T("Lost Password"), _href=URL(f="user", args="retrieve_password"), _class="action-lnk"))}}

{{=login_form}}
{{if auth.settings.facebook:}}

{{=T("Login with Facebook")}}
{{pass}}
{{if auth.settings.google:}}

{{=T("Login with Google")}}
{{pass}}


text:
package org.uberfire.workbench.model.menu;

import java.util.List;
import java.util.Map;

import jsinterop.annotations.JsType;

/**
 * Menus that includes permission
 */
@JsType
public interface Menus {

    /**
     * Returns the items in this collection of menus, in the order they should appear in the user interface.
     */
    public List<MenuItem> getItems();

    @Deprecated
    public Map<Object, MenuItem> getItemsMap();

    /**
     * Causes the given {@link MenuVisitor} to visit this menu, then each item in turn (they will pass the visitor to
     * their descendants). The menu items will be visited via an pre-order traversal (parents are visited before their
     * children). Top-level menu items are visited in the same order as they are returned from {@link #getItems()}.
     */
    public void accept( MenuVisitor visitor );

    /**
     * Defines the order on what these menus will be inserted.
     */
    public int getOrder();
}


text:
$:.unshift(File.expand_path('../../lib', __FILE__))
$:.unshift(File.expand_path('../../../aws-sdk-core/features', __FILE__))
$:.unshift(File.expand_path('../../../aws-sdk-core/lib', __FILE__))
$:.unshift(File.expand_path('../../../aws-sigv4/lib', __FILE__))

require 'features_helper'
require 'aws-sdk-kinesisvideosignalingchannels'

Aws::KinesisVideoSignalingChannels::Client.add_plugin(ApiCallTracker)


text:
require 'spec_helper'

describe Contentful::Bootstrap::OAuthEchoView do
  describe 'instance methods' do
    it '#render' do
      expect(subject.render).to include(
        'html',
        'script',
        'access_token',
        'window.location.replace',
        'save_token'
      )
    end
  end
end

describe Contentful::Bootstrap::ThanksView do
  describe 'instance methods' do
    it '#render' do
      expect(subject.render).to include(
        'html',
        'Contentful Bootstrap',
        'Thanks!'
      )
    end
  end
end

describe Contentful::Bootstrap::IndexController do
  subject { Contentful::Bootstrap::IndexController.new(ServerDouble.new) }

  describe 'instance methods' do
    describe '#do_GET' do
      it 'launches browser' do
        expect(Launchy).to receive(:open)
        subject.do_GET(RequestDouble.new, ResponseDouble.new)
      end
    end
  end
end

describe Contentful::Bootstrap::OAuthCallbackController do
  subject { Contentful::Bootstrap::OAuthCallbackController.new(ServerDouble.new) }
  let(:response_double) { ResponseDouble.new }

  describe 'instance methods' do
    describe '#do_GET' do
      it 'renders OAuthEchoView' do
        subject.do_GET(RequestDouble.new, response_double)
        expect(response_double.body).to eq Contentful::Bootstrap::OAuthEchoView.new.render
      end
    end
  end
end

describe Contentful::Bootstrap::SaveTokenController do
  let(:path) { File.expand_path(File.join('spec', 'fixtures', 'ini_fixtures', 'contentfulrc.ini')) }
  let(:token) { Contentful::Bootstrap::Token.new path }
  subject { Contentful::Bootstrap::SaveTokenController.new(ServerDouble.new, token) }
  let(:response_double) { ResponseDouble.new }
  let(:request_double) { RequestDouble.new }

  describe 'instance methods' do
    describe '#do_GET' do
      it 'writes token' do
        request_double.query = {'token' => 'foo'}

        expect(token).to receive(:write).with('foo')

        subject.do_GET(request_double, response_double)
      end

      it 'renders ThanksView' do
        request_double.query = {'token' => 'foo'}
        allow(token).to receive(:write)

        subject.do_GET(request_double, response_double)

        expect(response_double.body).to eq Contentful::Bootstrap::ThanksView.new.render
      end
    end
  end

  describe 'attributes' do
    it ':token' do
      expect(subject.token).to eq token
    end
  end
end

describe Contentful::Bootstrap::Server do
  let(:path) { File.expand_path(File.join('spec', 'fixtures', 'ini_fixtures', 'contentfulrc.ini')) }
  let(:token) { Contentful::Bootstrap::Token.new path }
  subject { Contentful::Bootstrap::Server.new(token) }

  before do
    allow_any_instance_of(WEBrick::HTTPServer).to receive(:start)
    allow(WEBrick::Utils).to receive(:create_listeners) { [] } # Mock TCP Port binding
  end

  describe 'instance methods' do
    describe '#start' do
      it 'runs server in a new thread' do
        expect(Thread).to receive(:new)
        subject.start
      end
    end

    describe '#stop' do
      it 'shutdowns webrick' do
        expect(subject.server).to receive(:shutdown)
        subject.stop
      end
    end

    describe '#running?' do
      it 'returns true if webrick is running' do
        expect(subject.server).to receive(:status) { :Running }
        expect(subject.running?).to be_truthy
      end

      it 'returns false if webrick is not running' do
        expect(subject.server).to receive(:status) { :Stop }
        expect(subject.running?).to be_falsey
      end
    end
  end

  describe 'attributes' do
    describe ':server' do
      it 'creates the webrick server' do
        expect(subject.server).to be_kind_of(WEBrick::HTTPServer)
      end

      describe 'mounted endpoints' do
        before do
          @mount_table = subject.server.instance_variable_get(:@mount_tab)
        end

        it '/' do
          expect(@mount_table['/'][0]).to eq(Contentful::Bootstrap::IndexController)
        end

        it '/oauth_callback' do
          expect(@mount_table['/oauth_callback'][0]).to eq(Contentful::Bootstrap::OAuthCallbackController)
        end

        it '/save_token' do
          expect(@mount_table['/save_token'][0]).to eq(Contentful::Bootstrap::SaveTokenController)
        end
      end
    end
  end
end


text:
<?php declare(strict_types = 1);

namespace Dms\Web\Laravel\Http\Controllers\Auth;

use Dms\Common\Structure\Web\EmailAddress;
use Dms\Core\Auth\IAdmin;
use Dms\Core\ICms;
use Dms\Web\Laravel\Auth\Password\IPasswordResetService;
use Dms\Web\Laravel\Http\Controllers\DmsController;
use Illuminate\Auth\Passwords\PasswordBrokerManager;
use Illuminate\Contracts\Auth\PasswordBroker;
use Illuminate\Http\Request;
use Illuminate\Mail\Message;

/**
 * The password reset controller
 *
 * @author Elliot Levin <elliotlevin@hotmail.com>
 */
class PasswordController extends DmsController
{
    /**
     * @var PasswordBroker
     */
    protected $passwordBroker;

    /**
     * @var IPasswordResetService
     */
    protected $passwordResetService;

    /**
     * Create a new password controller instance.
     *
     * @param ICms                  $cms
     * @param PasswordBrokerManager $passwordBrokerManager
     * @param IPasswordResetService $passwordResetService
     */
    public function __construct(ICms $cms, PasswordBrokerManager $passwordBrokerManager, IPasswordResetService $passwordResetService)
    {
        parent::__construct($cms);

        $this->middleware('dms.guest');
        $this->passwordBroker       = $passwordBrokerManager->broker('dms');
        $this->passwordResetService = $passwordResetService;
    }

    /**
     * Display the form to request a password reset link.
     *
     * @return \Illuminate\Http\Response
     */
    public function showResetLinkEmailForm()
    {
        return view('dms::auth.password.forgot');
    }

    /**
     * Send a reset link to the given user.
     *
     * @param  \Illuminate\Http\Request $request
     *
     * @return \Illuminate\Http\Response
     */
    public function sendResetLinkEmail(Request $request)
    {
        $this->validate($request, ['email' => 'required|email']);

        $credentials = ['emailAddress' => new EmailAddress($request->get('email'))];
        $response    = $this->passwordBroker->sendResetLink($credentials);

        switch ($response) {
            case PasswordBroker::RESET_LINK_SENT:
                return redirect()->back()->with('success', trans($response));

            case PasswordBroker::INVALID_USER:
                return redirect()->back()->withErrors(['email' => trans($response)]);
        }
    }

    /**
     * Display the password reset view for the given token.
     *
     * If no token is present, display the link request form.
     *
     * @param  string|null $token
     *
     * @return \Illuminate\Http\Response
     */
    public function showPasswordResetForm(string $token = null)
    {
        if (!$token) {
            return $this->showResetLinkEmailForm();
        }

        return view('dms::auth.password.reset')->with('token', $token);
    }

    /**
     * Reset the given user's password.
     *
     * @param  \Illuminate\Http\Request $request
     *
     * @return \Illuminate\Http\Response
     */
    public function reset(Request $request)
    {
        $this->validate($request, [
            'token'    => 'required',
            'username' => 'required',
            'password' => 'required|confirmed|min:6|max:50',
        ]);

        $credentials = $request->only(
            'username', 'password', 'password_confirmation', 'token'
        );

        $response = $this->passwordBroker->reset($credentials, function (IAdmin $user, $password) {
            $this->passwordResetService->resetUserPassword($user, $password);
        });

        switch ($response) {
            case PasswordBroker::PASSWORD_RESET:
                return redirect()->route('dms::auth.login')->with('success', trans($response));

            default:
                return redirect()->back()
                    ->withInput($request->only('email'))
                    ->withErrors(['email' => trans($response)]);
        }
    }
}


text:
/**
 * this is a wrapper around the zxcvbn2 password strength result function.
 * It's purpose is to strip all plain text passwords and tokens thereof, allowing
 * more ethically correct logs of password strength statistics.
 * @param result zxcvbn result, version 4.2.0 (29.11.2015)
 * @returns {*}
 */
function anonymizeResult(result){

    var anonymous_match_sequence = [];
    var password = result.password;
    var uppercaseMatches = password.match(/[A-Z]/g);
    var lowercaseMatches = password.match(/[a-z]/g);
    var digits = password.match(/[0-9]/g);
    var specialChars = password.match(/[@'#\.\$;%\^&\+=!"\(\)\*,-\/:<>\?§ ]/g);

    result.length = password.length;
    // we don't want to save the password in plain text.
    delete result.password;
    delete result.feedback;

    if(result.sequence){
        result.sequence.forEach(function(matchObj){
            delete matchObj.token;
            delete matchObj.matched_word;
            delete matchObj.sub_display;
            delete matchObj.graph;

            // we can't store stuff in the mongodb that has a dollar in it!
            // so we replace that key with "char_$"
            if(matchObj.sub && matchObj.sub['$']){
                matchObj.sub['char_$'] = matchObj.sub['$'];
                delete matchObj.sub['$'];
            }
            anonymous_match_sequence.push(matchObj);
        });
    }

    result.sequence = anonymous_match_sequence;
    result.lowercase = lowercaseMatches ? lowercaseMatches.length : 0;
    result.uppercase = uppercaseMatches ? uppercaseMatches.length : 0;
    result.digits = digits ? digits.length : 0;
    result.specialChars = specialChars ? specialChars.length : 0;
    return result;
}


text:
id: 587d7b7d367417b2b2512b1c
title: Check if an Object has a Property
challengeType: 1
---

## Description

Now we can add, modify, and remove keys from objects. But what if we just wanted to know if an object has a specific property? JavaScript provides us with two different ways to do this. One uses the hasOwnProperty() method and the other uses the in keyword. If we have an object users with a property of Alan, we could check for its presence in either of the following ways:

users.hasOwnProperty('Alan');
'Alan' in users;
// both return true

## Instructions

We've created an object, users, with some users in it and a function isEveryoneHere, which we pass the users object to as an argument. Finish writing this function so that it returns true only if the users object contains all four names, Alan, Jeff, Sarah, and Ryan, as keys, and false otherwise.

## Tests

```yml
tests:
  - text: The <code>users</code> object only contains the keys <code>Alan</code>, <code>Jeff</code>, <code>Sarah</code>, and <code>Ryan</code>
    testString: assert('Alan' in users && 'Jeff' in users && 'Sarah' in users && 'Ryan' in users && Object.keys(users).length === 4, 'The <code>users</code> object only contains the keys <code>Alan</code>, <code>Jeff</code>, <code>Sarah</code>, and <code>Ryan</code>');
  - text: The function <code>isEveryoneHere</code> returns <code>true</code> if <code>Alan</code>, <code>Jeff</code>, <code>Sarah</code>, and <code>Ryan</code> are properties on the <code>users</code> object
    testString: assert(isEveryoneHere(users) === true, 'The function <code>isEveryoneHere</code> returns <code>true</code> if <code>Alan</code>, <code>Jeff</code>, <code>Sarah</code>, and <code>Ryan</code> are properties on the <code>users</code> object');
  - text: The function <code>isEveryoneHere</code> returns <code>false</code> if <code>Alan</code>, <code>Jeff</code>, <code>Sarah</code>, and <code>Ryan</code> are not properties on the <code>users</code> object
    testString: assert((function() { delete users.Alan; delete users.Jeff; delete users.Sarah; delete users.Ryan; return isEveryoneHere(users) })() === false, 'The function <code>isEveryoneHere</code> returns <code>false</code> if <code>Alan</code>, <code>Jeff</code>, <code>Sarah</code>, and <code>Ryan</code> are not properties on the <code>users</code> object');

```

## Challenge Seed

```js
let users = {
  Alan: {
    age: 27,
    online: true
  },
  Jeff: {
    age: 32,
    online: true
  },
  Sarah: {
    age: 48,
    online: true
  },
  Ryan: {
    age: 19,
    online: true
  }
};

function isEveryoneHere(obj) {
  // change code below this line

  // change code above this line
}

console.log(isEveryoneHere(users));
```

## Solution

```js
let users = {
  Alan: {
    age: 27,
    online: true
  },
  Jeff: {
    age: 32,
    online: true
  },
  Sarah: {
    age: 48,
    online: true
  },
  Ryan: {
    age: 19,
    online: true
  }
};

function isEveryoneHere(obj) {
  return [
    'Alan',
    'Jeff',
    'Sarah',
    'Ryan'
  ].every(i => obj.hasOwnProperty(i));
}

console.log(isEveryoneHere(users));
```


text:
hello-world
===========

Yet Another Repository to test a workflow based on GitHub

Tonight I've discovered the true power of GitHub and Pull Requests started to make sense. Great stuff guys!


text:
package ca.uhn.fhir.jpa.search.warm;

import ca.uhn.fhir.context.ConfigurationException;
import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.context.RuntimeResourceDefinition;
import ca.uhn.fhir.jpa.api.config.DaoConfig;
import ca.uhn.fhir.jpa.api.dao.DaoRegistry;
import ca.uhn.fhir.jpa.api.dao.IFhirResourceDao;
import ca.uhn.fhir.jpa.api.model.WarmCacheEntry;
import ca.uhn.fhir.jpa.model.sched.HapiJob;
import ca.uhn.fhir.jpa.model.sched.ISchedulerService;
import ca.uhn.fhir.jpa.model.sched.ScheduledJobDefinition;
import ca.uhn.fhir.jpa.searchparam.MatchUrlService;
import ca.uhn.fhir.jpa.searchparam.SearchParameterMap;
import ca.uhn.fhir.util.UrlUtil;
import org.apache.commons.lang3.time.DateUtils;
import org.quartz.JobExecutionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Component
public class CacheWarmingSvcImpl implements ICacheWarmingSvc {

	private static final Logger ourLog = LoggerFactory.getLogger(CacheWarmingSvcImpl.class);
	@Autowired
	private DaoConfig myDaoConfig;
	private Map<WarmCacheEntry, Long> myCacheEntryToNextRefresh = new LinkedHashMap<>();
	@Autowired
	private FhirContext myCtx;
	@Autowired
	private DaoRegistry myDaoRegistry;
	@Autowired
	private MatchUrlService myMatchUrlService;
	@Autowired
	private ISchedulerService mySchedulerService;

	@Override
	public synchronized void performWarmingPass() {
		ourLog.trace("Starting cache warming pass for {} tasks", myCacheEntryToNextRefresh.size());

		for (WarmCacheEntry nextCacheEntry : new ArrayList<>(myCacheEntryToNextRefresh.keySet())) {

			long nextRefresh = myCacheEntryToNextRefresh.get(nextCacheEntry);
			if (nextRefresh < System.currentTimeMillis()) {

				// Perform the search
				refreshNow(nextCacheEntry);

				// Set the next time to warm this search
				nextRefresh = nextCacheEntry.getPeriodMillis() + System.currentTimeMillis();
				myCacheEntryToNextRefresh.put(nextCacheEntry, nextRefresh);

			}

		}

	}

	private void refreshNow(WarmCacheEntry theCacheEntry) {
		String nextUrl = theCacheEntry.getUrl();

		RuntimeResourceDefinition resourceDef = UrlUtil.parseUrlResourceType(myCtx, nextUrl);
		IFhirResourceDao<?> callingDao = myDaoRegistry.getResourceDao(resourceDef.getName());
		String queryPart = parseWarmUrlParamPart(nextUrl);
		SearchParameterMap responseCriteriaUrl = myMatchUrlService.translateMatchUrl(queryPart, resourceDef);

		callingDao.search(responseCriteriaUrl);
	}

	private String parseWarmUrlParamPart(String theNextUrl) {
		int paramIndex = theNextUrl.indexOf('?');
		if (paramIndex == -1) {
			throw new ConfigurationException("Invalid warm cache URL (must have ? character)");
		}
		return theNextUrl.substring(paramIndex);
	}

	@PostConstruct
	public void start() {
		initCacheMap();
		scheduleJob();
	}

	public void scheduleJob() {
		ScheduledJobDefinition jobDetail = new ScheduledJobDefinition();
		jobDetail.setId(getClass().getName());
		jobDetail.setJobClass(Job.class);
		mySchedulerService.scheduleClusteredJob(10 * DateUtils.MILLIS_PER_SECOND, jobDetail);
	}

	public static class Job implements HapiJob {
		@Autowired
		private ICacheWarmingSvc myTarget;

		@Override
		public void execute(JobExecutionContext theContext) {
			myTarget.performWarmingPass();
		}
	}

	public synchronized Set<WarmCacheEntry> initCacheMap() {

		myCacheEntryToNextRefresh.clear();
		List<WarmCacheEntry> warmCacheEntries = myDaoConfig.getWarmCacheEntries();
		for (WarmCacheEntry next : warmCacheEntries) {

			// Validate
			parseWarmUrlParamPart(next.getUrl());
			UrlUtil.parseUrlResourceType(myCtx, next.getUrl());

			myCacheEntryToNextRefresh.put(next, 0L);
		}

		return Collections.unmodifiableSet(myCacheEntryToNextRefresh.keySet());
	}
}


text:
import objectdraw.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

/**
 * This class shows how to create a menu bar GUI component
 * and use it to cause actions to occur.
 */
public class GUI_menu extends FrameWindowController implements ActionListener {

  JMenuBar myMenuBar;                               // the menubar
  JMenu colorMenu,shapeMenu,greenMenu;              // some menus for the menubar
  // the following are items in the three menus
  JMenuItem redItem,blueItem,greenLight,greenMedium,greenDark,square,circle,line;

  Color color=Color.RED;
  GraphicalObject graphicalObject=GraphicalObject.SQUARE; /* keeps track of which
                                                           * graphical object to draw*/
  Location oldPoint; // used to hold initial point in a line
  boolean lineStarted=false; /* if false, it means we click for the first point. If
                                true, it means that the click will draw the line.*/
   /**
   * begin serves as the costructor for a FrameWindowController (as always). In this
   * case it creates the GUI components, sets up their action responses, and adds the
   * components to the FrameWindowController. For this program, the GUI components
   * are all part of the menu bar placed on top of the screen.
   */
  public void begin() {
    myMenuBar=new JMenuBar();  //creates the menu bar on top of the screen
    setJMenuBar(myMenuBar);    //makes myMenuBar the top menu bar

    colorMenu=new JMenu("Color"); //create a menu for changing colors

    redItem=new JMenuItem("Red");    //create an item to handle the Red color
    colorMenu.add(redItem);          //add it to the Color Menu
    redItem.addActionListener(this); /*Make this class an ActionListener to react to this
                                      * menu item being clicked. */
    greenMenu=new JMenu("Green Menu"); //Create a submenu for green items.
    colorMenu.add(greenMenu);          //add the Green submenu to the Color Menu
    greenLight=new JMenuItem("Light Green"); //a Light Green Item
    greenLight.addActionListener(this);      //add this as the Light Green action listener
    greenMenu.add(greenLight);               //add the Light Green Item to the green menu
    greenMedium=new JMenuItem("Medium Green"); //Create a medium green item
    greenMedium.addActionListener(this);       //add this as the Medium Green action listener
    greenMenu.add(greenMedium);                //add Medium Green to the green menu
    greenDark=new JMenuItem("Dark Green"); //a bright green item
    greenDark.addActionListener(this);       //add this as the Bright Green action listener
    greenMenu.add(greenDark);                //add Bright Green to the green menu

    blueItem=new JMenuItem("Blue");      //create a Blue Item
    blueItem.addActionListener(this);    //add this as the Blue action listener
    colorMenu.add(blueItem);             //add the Blue Item to the color menu
    myMenuBar.add(colorMenu);            //add the Color Menu to the Menu Bar

    shapeMenu=new JMenu("Shape");        //create a shape menu
    square=new JMenuItem("Square");      //create a square item
    square.addActionListener(this);      //add this as the square action listener
    shapeMenu.add(square);               //add the square to the shape menu
    circle=new JMenuItem("Circle");      //create a circle item
    circle.addActionListener(this);      //add this as the circle action listener
    shapeMenu.add(circle);               //add the circle to the shape menu
    line=new JMenuItem("Line");          //add the line object to the shape menu
    line.addActionListener(this);        //add this as the line action listener
    shapeMenu.add(line);                 //add line to the shape menu
    myMenuBar.add(shapeMenu);            //add the shape menu to the menu bar

    getContentPane().validate();         //validate the GUI components we have added.
  }

  /**
   * onMouseClick draws the appropriate thing in the current color at the appropriate
   * spot.
   */
  public void actionPerformed(ActionEvent evt) {
    Object actionObject=evt.getSource();
    if(actionObject==redItem) {
      color=Color.RED;
    }
    else if(actionObject==blueItem) {    // and, also, for all the menu items
      color=Color.BLUE;
    }
    else if(actionObject==greenLight) {
      color=new Color(0,255,0);
    }
    else if(actionObject==greenMedium) {
      color=new Color(0,205,0);
    }
    else if(actionObject==greenDark) {
      color=new Color(0,155,0);
    }
    else if(actionObject==square) {
      graphicalObject=GraphicalObject.SQUARE;
    }
    else if(actionObject==circle) {
      graphicalObject=GraphicalObject.CIRCLE;
    }
    else if(actionObject==line) {
      graphicalObject=GraphicalObject.LINE;
    }
  }

  /**
   * onMouseClick actually draws the correct object in Color color.
   */
  public void onMouseClick(Location point) {
    switch(graphicalObject) {
      case SQUARE:
        new FilledRect(point,50,50,canvas).setColor(color); break;
      case CIRCLE:
        new FilledOval(point,50,50,canvas).setColor(color); break;
      case LINE:
        if(lineStarted) {
          new Line(oldPoint,point,canvas).setColor(color);
          lineStarted=false;
        }
        else {
          oldPoint=point;
          lineStarted=true;
        } break;
    }
  }
}


text:
class Example implements component
{
    function __construct($command = null)
    {
        $this->db = startsql();
        if($command == null)
        {
            $this->makeTable();
        }
        $this->components = "No Components";
    }
    public function title()
    {
        return "Example Class";
    }

    public function table ()
    {
        return "
Table not implemented
";
    }

    public function modComponent($id,$data)
    {
        ;
    }
    public function useComponent($id,$data)
    {
        ;
    }
    public function addComponent($data)
    {
        ;
    }
    public function delComponent($id)
    {
        ;
    }
    public function makeTable()
    {
        ;
    }
    public function content()
    {
        echo "
This is an example
\n";
    }
    public function jscript()
    {
        return"";
    }
    public function form()
    {
        echo "";
    }
}


text:
<?php
declare(strict_types = 1);

namespace Innmind\TimeContinuum\Earth\Timezone\Europe;

use Innmind\TimeContinuum\Earth\Timezone;

/**
 * @psalm-immutable
 */
final class Vatican extends Timezone
{
    public function __construct()
    {
        parent::__construct('Europe/Vatican');
    }
}


text:
require 'spec_helper'

describe Api::SchedulesController do
  include Devise::TestHelpers

  describe '#index' do

    let(:user) { FactoryGirl.create(:user) }

    it 'lists all schedules for a user' do
      sign_in user
      schedules = FactoryGirl
                    .create_list(:schedule, 2, device: user.device)
                    .map(&:_id)
                    .map(&:to_s)
                    .sort
      get :index
      expect(response.status).to eq(200)
      expect(json.length).to eq(2)
      expect(json.map{ |s| s[:_id] }.sort).to eq(schedules)
    end
  end
end


text:
import angular from 'angular'
import gql from 'graphql-tag';
import { ApolloClient, createNetworkInterface } from 'apollo-client';
import {SubscriptionClient, addGraphQLSubscriptions} from 'subscriptions-transport-ws';

class ApolloCarService {
    // static $inject =
    /*@ngInject*/
    constructor($http) {
        this.$http = $http;
        let networkInterface = createNetworkInterface({uri: 'http://localhost:8080/graphql'});
        // Create WebSocket client
        const wsClient = new SubscriptionClient(`ws://localhost:8090/`, {
            reconnect: true,
            // connectionParams: {
            //     // Pass any arguments you want for initialization
            // }
        });
        const networkInterfaceWithSubscriptions = addGraphQLSubscriptions(
            networkInterface,
            wsClient
        );
        this.client = new ApolloClient({
            networkInterface: networkInterfaceWithSubscriptions
        });

        this.createServiceSubscriptions();
    }
    createServiceSubscriptions(){
        this.clientUpdateSubscription = this.client.subscribe({
            query: gql`

                subscription onCarUpdated{
                            carUpdated {
                                _id
                                name
                                speed
                            }
                        }`,
            variables: {},
        })
        this.clientAddSubscription = this.client.subscribe({
            query: gql`
                subscription onCarAdded{
                            carAdded {
                                _id
                                name
                                speed
                            }
                        }`,
            variables: {},
        })
        this.clientDeleteSubscription = this.client.subscribe({
            query: gql`
                subscription onCarDeleted{
                        carDeleted {
                                _id
                                name
                            }
                        }`,
            variables: {},
        })
    }

    getAllCars() {
        return this.client.query({
            query: gql`
                query car{
                    car{
                        _id
                        name
                        speed
                    }
                }`
        })
    }

    addNewCar (car) {
        let addCarParams = 'name: "' + car.name + '"';
        if (car.speed) {
            addCarParams += ', speed: ' + car.speed;
        }
        return this.client.mutate({
            mutation: gql`
                mutation {
                    addCar(${addCarParams}) {
                        name
                        speed
                    }
                }
            `,
        })
    }

    editCar(previousName, currentName, currentSpeed) {
        let prevQuotedName = '"' + previousName + '"';
        let currentQuotedName = '"' + currentName + '"';
        return this.client.mutate({
            mutation: gql`
                mutation {
                    updateCar(currName : ${prevQuotedName}, newName : ${currentQuotedName}, newSpeed: ${currentSpeed}) {
                        name
                        speed
                    }
                }
            `,
        })
    }
    deleteCar(name) {
        let quotedName = '"' + name + '"';
        return this.client.mutate({
            mutation: gql`
                mutation {
                    deleteCar(name : ${quotedName}) {
                        _id
                        name
                    }
                }
            `,
        })
    }

    subscribeToUpdates() {
        return this.clientUpdateSubscription;
    }
    subscribeToAdds() {
        return this.clientAddSubscription;
    }
    subscribeToDeletes() {
        return this.clientDeleteSubscription;
    }

}

export default ApolloCarService


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>de.fhg.igd</groupId>
    <artifactId>equinox-test</artifactId>
    <version>1.2.0-SNAPSHOT</version>
    <relativePath>../pom.xml</relativePath>
  </parent>
  <groupId>de.fhg.igd</groupId>
  <artifactId>de.fhg.igd.equinox.test.site</artifactId>
  <version>1.2.0-SNAPSHOT</version>
  <packaging>eclipse-repository</packaging>
</project>


text:
package com.dxjia.doubantop.fragments;

import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.dxjia.doubantop.R;
import com.dxjia.doubantop.interfaces.SearchStateToggleListener;
import com.dxjia.doubantop.net.DoubanApiUtils;

import butterknife.InjectView;

/**
 * Created by 德祥 on 2015/7/14.
 */
public class SearchPagerFragment extends BaseFragment {

    @InjectView(R.id.empty_view)
    TextView mEmptyView;

    @InjectView(R.id.search_result_container)
    FrameLayout mSearchResultContainer;

    private String mSearchKey;

    private MovieListFragment mSearchResultFragment;

    private SearchStateToggleListener mSearchStateToggleListener;

    @Override
    protected int getLayout() {
        return R.layout.search_pager_fragment;
    }

    public static SearchPagerFragment newInstance() {
        return new SearchPagerFragment();
    }

    public SearchPagerFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mSearchResultFragment = MovieListFragment.newInstance(DoubanApiUtils.API_TYPE_SEARCH);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initViews();
        updateViews();
    }

    private void initViews() {
        // setup search result container fragment
        FragmentManager fm = getChildFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();
        transaction.replace(R.id.search_result_container, mSearchResultFragment, "SearchContentFragment");
        transaction.commit();

        mEmptyView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mSearchStateToggleListener != null) {
                    mSearchStateToggleListener.toggleSearchState();
                }
            }
        });
    }

    private void updateViews() {
        if (TextUtils.isEmpty(mSearchKey)) {
            mEmptyView.setVisibility(View.VISIBLE);
            mSearchResultContainer.setVisibility(View.INVISIBLE);
        } else {
            mEmptyView.setVisibility(View.INVISIBLE);
            mSearchResultContainer.setVisibility(View.VISIBLE);
        }
    }

    public void setSearchStateToggleListener(SearchStateToggleListener l) {
        mSearchStateToggleListener = l;
    }

    public void startSearch(String key) {
        if (TextUtils.isEmpty(key)) {
            return;
        }

        mSearchKey = key;
        updateViews();
        if (mSearchResultFragment != null) {
            mSearchResultFragment.startNewSearch(key);
        }
    }
}


text:
'use strict';

const common = require('../common');

if (!common.enoughTestMem)
  common.skip('intensive toString tests due to memory confinements');

const assert = require('assert');
const fs = require('fs');
const path = require('path');
const cp = require('child_process');
const kStringMaxLength = process.binding('buffer').kStringMaxLength;
if (common.isAIX && (Number(cp.execSync('ulimit -f')) * 512) < kStringMaxLength)
  common.skip('intensive toString tests due to file size confinements');

const tmpdir = require('../common/tmpdir');
tmpdir.refresh();

const file = path.join(tmpdir.path, 'toobig.txt');
const stream = fs.createWriteStream(file, {
  flags: 'a'
});

const size = kStringMaxLength / 200;
const a = Buffer.alloc(size, 'a');

for (let i = 0; i < 201; i++) {
  stream.write(a);
}

stream.end();
stream.on('finish', common.mustCall(function() {
  fs.readFile(file, 'utf8', common.mustCall(function(err, buf) {
    assert.ok(err instanceof Error);
    if (err.message !== 'Array buffer allocation failed') {
      const stringLengthHex = kStringMaxLength.toString(16);
      common.expectsError({
        message: 'Cannot create a string longer than ' +
                 `0x${stringLengthHex} characters`,
        code: 'ERR_STRING_TOO_LONG',
        type: Error
      })(err);
    }
    assert.strictEqual(buf, undefined);
  }));
}));

function destroy() {
  try {
    fs.unlinkSync(file);
  } catch (err) {
    // it may not exist
  }
}

process.on('exit', destroy);

process.on('SIGINT', function() {
  destroy();
  process.exit();
});

// To make sure we don't leave a very large file
// on test machines in the event this test fails.
process.on('uncaughtException', function(err) {
  destroy();
  throw err;
});