text:
<bill session="110" type="sr" number="510" updated="2009-01-09T21:01:56-05:00">
	<status><vote date="1209009600" datetime="2008-04-24" where="s" result="pass" how="by Unanimous Consent" roll=""/></status>

	<introduced date="1207800000" datetime="2008-04-10"/>
	<titles>
		<title type="official" as="introduced">A resolution supporting the goals and ideals of National Cystic Fibrosis Awareness Month.</title>
	</titles>
	<sponsor id="300076"/>
	<cosponsors>
		<cosponsor id="400272" joined="2008-04-21"/>
		<cosponsor id="300055" joined="2008-04-10"/>
	</cosponsors>
	<actions>
		<action date="1207800000" datetime="2008-04-10"><text>Referred to the Committee on Health, Education, Labor, and Pensions.</text><reference label="text of measure as introduced" ref="CR S2950"/></action>
		<action date="1209009600" datetime="2008-04-24"><text>Senate Committee on Health, Education, Labor, and Pensions discharged by Unanimous Consent.</text><reference label="consideration" ref="CR S3412"/></action>
		<vote date="1209009600" how="by Unanimous Consent" datetime="2008-04-24" where="s" type="vote" result="pass" ><text>Resolution agreed to in Senate without amendment and with a preamble by Unanimous Consent.</text><reference label="text" ref="CR S3412"/></vote>
	</actions>
	<committees>

	</committees>
	<relatedbills>

	</relatedbills>
	<subjects>

	</subjects>
	<amendments>

	</amendments>
	<summary>
	4/24/2008--Passed Senate without amendment. (This measure has not been amended since it was introduced. The summary of that version is repeated here.) Honors the goals and ideals of National Cystic Fibrosis Awareness Month. Encourages early diagnosis and access to quality care for people with cystic fibrosis. Expresses support for research to find a cure by fostering an enhanced research program through a strong federal commitment and expanded public-private partnerships.<br/>
	</summary>
</bill>


text:
@implementation LUTFormatterHaldCLUT

+ (void)load{
    [super load];
}

#if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR

//maybe implement someday

#elif TARGET_OS_MAC

+(LUT *)LUTFromURL:(NSURL *)fileURL{
    LUT *lut = [super LUTFromURL:fileURL];
    if (!lut) {
        return nil;
    }
    else{
        NSMutableDictionary *exposedPassthroughOptions = [lut.passthroughFileOptions[[self formatterID]] mutableCopy];
        exposedPassthroughOptions[@"lutSize"] = @(lut.size);
        lut.passthroughFileOptions = @{[self formatterID] : [NSDictionary dictionaryWithDictionary:exposedPassthroughOptions]};
        return lut;
    }
}

+ (NSImage *)imageFromLUT:(LUT *)lut
                 bitdepth:(NSUInteger)bitdepth {

    LUT3D *lut3D = (LUT3D *)lut;

    if (sqrt(lut3D.size) != (double)((int)sqrt(lut3D.size))) {
        @throw [NSException exceptionWithName:@"HaldCLUTWriterError"
                                       reason:@"LUT size must be a whole number when square-rooted." userInfo:nil];
    }

    CGFloat width  = sqrt(lut3D.size * lut3D.size * lut3D.size);
    CGFloat height = width;

    NSBitmapImageRep *imageRep = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:NULL
                                                                         pixelsWide:width
                                                                         pixelsHigh:height
                                                                      bitsPerSample:bitdepth
                                                                    samplesPerPixel:3
                                                                           hasAlpha:NO
                                                                           isPlanar:NO
                                                                     colorSpaceName:NSDeviceRGBColorSpace
                                                                        bytesPerRow:(width * (bitdepth * 3)) / 8
                                                                    bitsPerPixel:bitdepth * 3];

    int cubeIndex = 0;
    for (int y = 0; y < height; y++) {
        for (int x = 0; x < width; x++) {
            int redIndex = cubeIndex % lut3D.size;
            int greenIndex = (cubeIndex % (lut3D.size * lut3D.size)) / (lut3D.size);
            int blueIndex = cubeIndex / (lut3D.size * lut3D.size);

            NSColor *color = [[lut3D colorAtR:redIndex g:greenIndex b:blueIndex].systemColor colorUsingColorSpaceName:NSDeviceRGBColorSpace];
            [imageRep setColor:color atX:x y:y];

            cubeIndex++;
        }
    }

    NSImage* image = [[NSImage alloc] initWithSize:NSMakeSize(width, height)];
    [image addRepresentation:imageRep];
    return image;
}

+ (LUT *)LUTFromImage:(NSImage *)image {

    NSBitmapImageRep *imageRep = [NSBitmapImageRep imageRepWithData:[image TIFFRepresentation]];

    if (imageRep.pixelsWide != imageRep.pixelsHigh) {
        @throw [NSException exceptionWithName:@"HaldCLUTReaderError"
                                       reason:@"Image width must be the same as the image height." userInfo:nil];
    }

    int lutSize = round(pow(pow(imageRep.pixelsWide, 2.0), 1.0/3.0));
    if (sqrt(lutSize) != (double)((int)sqrt(lutSize))) {
        @throw [NSException exceptionWithName:@"HaldCLUTReaderError"
                                       reason:@"LUT Size isn't square-rootable." userInfo:nil];
    }

    LUT3D *lut3D = [LUT3D LUTOfSize:lutSize inputLowerBound:0.0 inputUpperBound:1.0];

    int cubeIndex = 0;
    for (int y = 0; y < imageRep.pixelsHigh; y++) {
        for (int x = 0; x < imageRep.pixelsHigh; x++) {
            int redIndex = cubeIndex % lut3D.size;
            int greenIndex = (cubeIndex % (lut3D.size * lut3D.size)) / (lut3D.size);
            int blueIndex = cubeIndex / (lut3D.size * lut3D.size);

            [lut3D setColor:[LUTColor colorWithSystemColor:[imageRep colorAtX:x y:y]] r:redIndex g:greenIndex b:blueIndex];

            cubeIndex++;
        }
    }

    return lut3D;
}

+ (BOOL)isValidReaderForURL:(NSURL *)fileURL{
    if (![super isValidReaderForURL:fileURL]) {
        return NO;
    }

    NSImage *image = [[NSImage alloc] initWithContentsOfURL:fileURL];
    NSBitmapImageRep* imageRep = [NSBitmapImageRep imageRepWithData:[image TIFFRepresentation]];

    int lutSize = round(pow(pow(imageRep.pixelsWide, 2.0), 1.0/3.0));
    if (sqrt(lutSize) != (double)((int)sqrt(lutSize)) || lutSize > 64) {
        return NO;
    }
    else{
        return YES;
    }
}
#endif

+ (NSArray *)allOptions{
    NSMutableArray *sizeArray = [NSMutableArray array];

    for (int i = 3; i <= 8; i++) {
        [sizeArray addObject:@{[NSString stringWithFormat:@"%i", i*i] : @(i*i)}];
    }

    NSArray *superOptions = [super allOptions];
    NSMutableArray *newOptions = [NSMutableArray array];
    for (NSDictionary *option in superOptions) {
        NSDictionary *newOption = [option mutableCopy];
        [newOption setValue:M13OrderedDictionaryFromOrderedArrayWithDictionaries(sizeArray) forKey:@"lutSize"];
        [newOptions addObject:newOption];
    }

    return newOptions;
}

+ (NSDictionary *)defaultOptions{
    NSMutableDictionary *defaultsExposed = [[super defaultOptions][[self formatterID]] mutableCopy];
    defaultsExposed[@"lutSize"] = @(36);

    return @{[self formatterID] : defaultsExposed};
}

+ (NSString *)formatterName{
    return @"Hald CLUT";
}

+ (NSString *)formatterID{
    return @"haldCLUT";
}

@end

redpajama_set_name: RedPajamaGithub


text:
<?php

class RegisteredCap extends AppModel {
  public $useTable = 'registered_caps';
  public $name = 'RegisteredCap';

}
?>


text:
package test.xml.other;

import gov.nih.nci.cacoresdk.domain.other.datatype.EdTextDataType;
import gov.nih.nci.iso21090.Ed;
import gov.nih.nci.iso21090.EdText;
import gov.nih.nci.iso21090.NullFlavor;
import gov.nih.nci.system.applicationservice.ApplicationException;
import gov.nih.nci.system.client.util.xml.XMLUtilityException;
import gov.nih.nci.system.query.hibernate.HQLCriteria;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.LogicalExpression;
import org.hibernate.criterion.Property;
import org.hibernate.criterion.Restrictions;
import org.jdom.Document;

import test.gov.nih.nci.cacoresdk.SDKISOTestBase;

/*
 * Test case for EdText data type
 */
public class EdTextDataTypeXMLTest extends SDKISOTestBase
{

	/**
	 * Returns name of the test case
	 * @return
	 */
	public static String getTestCaseName()
	{
		return "EdText Datatype XML Test Case";
	}

	/**
	 * Search Value1 by detached criteria Test
	 *
	 * @throws ApplicationException
	 */
	@SuppressWarnings("unchecked")
	public void testEdTextValue1ByDetachedCriteria() throws ApplicationException
	{
		DetachedCriteria criteria = DetachedCriteria.forClass(EdTextDataType.class);
		criteria.add(Property.forName("value1").isNotNull());

		Collection<EdTextDataType> result = search(criteria, "gov.nih.nci.cacoresdk.domain.other.datatype.EdTextDataType");
		assertNotNull(result);
		assertEquals(5, result.size());
		assertValue1(result);
	}

	/**
	 * Search Value1 by HQL criteria Test
	 *
	 * @throws ApplicationException
	 */
	@SuppressWarnings("unchecked")
	public void testEdTextValue1ByHQLCriteria() throws ApplicationException
	{
		HQLCriteria criteria = new HQLCriteria("from gov.nih.nci.cacoresdk.domain.other.datatype.EdTextDataType a where a.value1.value is not null order by a.id asc");
		Collection<EdTextDataType> result = search(criteria, "gov.nih.nci.cacoresdk.domain.other.datatype.EdTextDataType");
		assertEquals(5, result.size());
		assertValue1(result);
	}

	/**
	 * Search Value2 by detached criteria Test
	 *
	 * @throws ApplicationException
	 */
	@SuppressWarnings("unchecked")
	public void testEdTextValue2ByDetachedCriteria() throws ApplicationException
	{
		DetachedCriteria criteria = DetachedCriteria.forClass(EdTextDataType.class);
		criteria.add(Restrictions.or(Property.forName("value2.value").isNotNull(), Property.forName("value2.nullFlavor").isNotNull()));

		Collection<EdTextDataType> result = search(criteria, "gov.nih.nci.cacoresdk.domain.other.datatype.EdTextDataType");
		assertNotNull(result);
		assertEquals(5, result.size());
		assertValue2(result);
	}

	/**
	 * Search Value2 by HQL criteria Test
	 *
	 * @throws ApplicationException
	 */
	@SuppressWarnings("unchecked")
	public void testEdTextValue2ByHQLCriteria() throws ApplicationException
	{
		HQLCriteria criteria = new HQLCriteria("from gov.nih.nci.cacoresdk.domain.other.datatype.EdTextDataType a where (a.value2.nullFlavor is not null or a.value2.value is not null) order by a.id asc");
		Collection<EdTextDataType> result = search(criteria, "gov.nih.nci.cacoresdk.domain.other.datatype.EdTextDataType");
		assertEquals(5, result.size());
		assertValue2(result);
	}

	/**
	 * Search Value3 by detached criteria Test
	 *
	 * @throws ApplicationException
	 */
	@SuppressWarnings("unchecked")
	public void testEdTextValue3ByDetachedCriteria() throws ApplicationException
	{
		DetachedCriteria criteria = DetachedCriteria.forClass(EdTextDataType.class);
		LogicalExpression exp1 = Restrictions.or(Property.forName("value3.data").isNotNull(), Property.forName("value3.nullFlavor").isNotNull());
		LogicalExpression exp2 = Restrictions.or(Property.forName("value3.value").isNotNull(), Property.forName("value3.compression").isNotNull());
		criteria.add(Restrictions.or(exp1, exp2));

		Collection<EdTextDataType> result = search(criteria, "gov.nih.nci.cacoresdk.domain.other.datatype.EdTextDataType");
		assertNotNull(result);
		assertEquals(5, result.size());
		assertValue3(result);
	}

	/**
	 * Search Value2 by HQL criteria Test
	 *
	 * @throws ApplicationException
	 */
	@SuppressWarnings("unchecked")
	public void testEdTextValue3ByHQLCriteria() throws ApplicationException
	{
		HQLCriteria criteria = new HQLCriteria("from gov.nih.nci.cacoresdk.domain.other.datatype.EdTextDataType a where (a.value3.nullFlavor is not null or a.value3.data is not null or a.value3.compression is not null or a.value3.value is not null) order by a.id asc");
		Collection<EdTextDataType> result = search(criteria, "gov.nih.nci.cacoresdk.domain.other.datatype.EdTextDataType");
		assertEquals(5, result.size());
		assertValue3(result);
	}

	/**
	 * Test all columns and rows for correct values
	 *
	 * @throws ApplicationException
	 */
	@SuppressWarnings("unchecked")
	public void testEdTextValue() throws ApplicationException
	{
		EdTextDataType searchObject = new EdTextDataType();
		Collection<EdTextDataType> result = search("gov.nih.nci.cacoresdk.domain.other.datatype.EdTextDataType",searchObject );
		assertValue1(result);
		assertValue2(result);
		assertValue3(result);
	}

	private void assertValue1(Collection<EdTextDataType> result)
	{
		assertNotNull(result);

		int counter = 1;
		for(EdTextDataType data : result)
		{
				assertNotNull(data);
				if(data.getValue1() == null)
					continue;

				try
				{
					String xmlFileName = getXMLFileName(data, counter);
					String schemaFileName = getSchemaFileName(data.getClass());
					//Marshall the object
					toXML(xmlFileName, data);
					Document document = getDocument(xmlFileName);
					//Validate the XML
					validateClassElements(document, data);
					assertTrue(validateXMLData(result, schemaFileName, xmlFileName));

					//Unmarshall XML to data object
					EdTextDataType unmarshalledData = (EdTextDataType)fromXML(xmlFileName);

					//Verify umarshalled object with original object
					assertTrue(compareValue1(data, unmarshalledData));
				}
				catch(IOException e)
				{
					e.printStackTrace();
				}
				catch(XMLUtilityException e)
				{
					e.printStackTrace();
				}
				catch (ClassNotFoundException e) {
					e.printStackTrace();
				}
				counter++;
		}
	}

	private void assertValue2(Collection<EdTextDataType> result)
	{
		assertNotNull(result);

		int counter = 1;
		for(EdTextDataType data : result)
		{
				assertNotNull(data);
				if(data.getValue2() == null)
					continue;

				try
				{
					String xmlFileName = getXMLFileName(data, counter);
					String schemaFileName = getSchemaFileName(data.getClass());
					//Marshall the object
					toXML(xmlFileName, data);
					Document document = getDocument(xmlFileName);
					//Validate the XML
					validateClassElements(document, data);
					assertTrue(validateXMLData(result, schemaFileName, xmlFileName));

					//Unmarshall XML to data object
					EdTextDataType unmarshalledData = (EdTextDataType)fromXML(xmlFileName);

					//Verify umarshalled object with original object
					assertTrue(compareValue2(data, unmarshalledData));
				}
				catch(IOException e)
				{
					e.printStackTrace();
				}
				catch(XMLUtilityException e)
				{
					e.printStackTrace();
				}
				catch (ClassNotFoundException e) {
					e.printStackTrace();
				}
				counter++;
		}
	}

	private void assertValue3(Collection<EdTextDataType> result)
	{
		assertNotNull(result);

		int counter = 1;
		for(EdTextDataType data : result)
		{
				assertNotNull(data);
				if(data.getValue3() == null)
					continue;

				try
				{
					String xmlFileName = getXMLFileName(data, counter);
					String schemaFileName = getSchemaFileName(data.getClass());
					//Marshall the object
					toXML(xmlFileName, data);
					Document document = getDocument(xmlFileName);
					//Validate the XML
					validateClassElements(document, data);
					assertTrue(validateXMLData(result, schemaFileName, xmlFileName));

					//Unmarshall XML to data object
					EdTextDataType unmarshalledData = (EdTextDataType)fromXML(xmlFileName);

					//Verify umarshalled object with original object
					assertTrue(compareValue3(data, unmarshalledData));
				}
				catch(IOException e)
				{
					e.printStackTrace();
				}
				catch(XMLUtilityException e)
				{
					e.printStackTrace();
				}
				catch (ClassNotFoundException e) {
					e.printStackTrace();
				}
				counter++;
		}
	}

	private boolean compareValue1(EdTextDataType actual, EdTextDataType result)
	{
		EdText aVal = actual.getValue1();
		assertNotNull(aVal);
		EdText rVal = result.getValue1();
		assertNotNull(rVal);
		return aVal.equals(rVal);
	}

	private boolean compareValue2(EdTextDataType actual, EdTextDataType result)
	{
		EdText aVal = actual.getValue2();
		assertNotNull(aVal);
		EdText rVal = result.getValue2();
		assertNotNull(rVal);
		return aVal.equals(rVal);
	}

	private boolean compareValue3(EdTextDataType actual, EdTextDataType result)
	{
		Ed aVal = actual.getValue3();
		assertNotNull(aVal);
		Ed rVal = result.getValue3();
		assertNotNull(rVal);
		return aVal.equals(rVal);
	}

}


text:
TEST_CASE("Invalid file descriptor of uncompressed file") {
    osmium::io::NoDecompressor decomp{-1};
    REQUIRE_THROWS_AS(decomp.read(), const std::system_error&);
}

TEST_CASE("Non-open file descriptor of uncompressed file") {
    // 12345 is just a random file descriptor that should not be open
    osmium::io::NoDecompressor decomp{12345};
    REQUIRE_THROWS_AS(decomp.read(), const std::system_error&);
}

TEST_CASE("Empty uncompressed file") {
    const int count = count_fds();

    const std::string input_file = with_data_dir("t/io/empty_file");
    const int fd = osmium::io::detail::open_for_reading(input_file);
    REQUIRE(fd > 0);

    osmium::io::NoDecompressor decomp{fd};
    REQUIRE(decomp.read().empty());
    decomp.close();

    REQUIRE(count == count_fds());
}

TEST_CASE("Read uncompressed file") {
    const int count = count_fds();

    const std::string input_file = with_data_dir("t/io/data.txt");
    const int fd = osmium::io::detail::open_for_reading(input_file);
    REQUIRE(fd > 0);

    size_t size = 0;
    std::string all;
    {
        osmium::io::NoDecompressor decomp{fd};
        for (std::string data = decomp.read(); !data.empty(); data = decomp.read()) {
            size += data.size();
            all += data;
        }
        decomp.close();
    }

    REQUIRE(size >= 9);
    all.resize(8);
    REQUIRE("TESTDATA" == all);

    REQUIRE(count == count_fds());
}

TEST_CASE("Read uncompressed file without explicit close") {
    const int count = count_fds();

    const std::string input_file = with_data_dir("t/io/data.txt");
    const int fd = osmium::io::detail::open_for_reading(input_file);
    REQUIRE(fd > 0);

    size_t size = 0;
    std::string all;
    {
        osmium::io::NoDecompressor decomp{fd};
        for (std::string data = decomp.read(); !data.empty(); data = decomp.read()) {
            size += data.size();
            all += data;
        }
    }

    REQUIRE(size >= 9);
    all.resize(8);
    REQUIRE("TESTDATA" == all);

    REQUIRE(count == count_fds());
}

TEST_CASE("Compressor: Invalid file descriptor for uncompressed file") {
    osmium::io::NoCompressor comp{-1, osmium::io::fsync::yes};
    REQUIRE_THROWS_AS(comp.write("foo"), const std::system_error&);
}

TEST_CASE("Compressor: Non-open file descriptor for uncompressed file") {
    // 12345 is just a random file descriptor that should not be open
    osmium::io::NoCompressor comp{12345, osmium::io::fsync::yes};
    REQUIRE_THROWS_AS(comp.write("foo"), const std::system_error&);
}

TEST_CASE("Write uncompressed file with explicit close") {
    const int count = count_fds();

    const std::string output_file = "test_uncompressed_out.txt";
    const int fd = osmium::io::detail::open_for_writing(output_file, osmium::io::overwrite::allow);
    REQUIRE(fd > 0);

    osmium::io::NoCompressor comp{fd, osmium::io::fsync::yes};
    comp.write("foo");
    comp.close();

    REQUIRE(count == count_fds());

    REQUIRE(osmium::file_size(output_file) == 3);
}

TEST_CASE("Write uncompressed file with implicit close") {
    const int count = count_fds();

    const std::string output_file = "test_uncompressed_out.txt";
    const int fd = osmium::io::detail::open_for_writing(output_file, osmium::io::overwrite::allow);
    REQUIRE(fd > 0);

    {
        osmium::io::NoCompressor comp{fd, osmium::io::fsync::yes};
        comp.write("foo");
    }
    REQUIRE(count == count_fds());

    REQUIRE(osmium::file_size(output_file) == 3);
}


text:
package shim

import (
	"context"
	"encoding/json"
	"fmt"
	"io"
	"path/filepath"
	"sync"
	"syscall"
	"time"

	"golang.org/x/sys/unix"

	"github.com/containerd/console"
	"github.com/containerd/containerd/identifiers"
	shimapi "github.com/containerd/containerd/linux/shim/v1"
	"github.com/containerd/fifo"
	runc "github.com/containerd/go-runc"
	specs "github.com/opencontainers/runtime-spec/specs-go"
	"github.com/pkg/errors"
)

type execProcess struct {
	wg sync.WaitGroup

	processState

	mu      sync.Mutex
	id      string
	console console.Console
	io      runc.IO
	status  int
	exited  time.Time
	pid     int
	closers []io.Closer
	stdin   io.Closer
	stdio   stdio
	path    string
	spec    specs.Process

	parent    *initProcess
	waitBlock chan struct{}
}

func newExecProcess(context context.Context, path string, r *shimapi.ExecProcessRequest, parent *initProcess, id string) (process, error) {
	if err := identifiers.Validate(id); err != nil {
		return nil, errors.Wrapf(err, "invalid exec id")
	}
	// process exec request
	var spec specs.Process
	if err := json.Unmarshal(r.Spec.Value, &spec); err != nil {
		return nil, err
	}
	spec.Terminal = r.Terminal

	e := &execProcess{
		id:     id,
		path:   path,
		parent: parent,
		spec:   spec,
		stdio: stdio{
			stdin:    r.Stdin,
			stdout:   r.Stdout,
			stderr:   r.Stderr,
			terminal: r.Terminal,
		},
		waitBlock: make(chan struct{}),
	}
	e.processState = &execCreatedState{p: e}
	return e, nil
}

func (e *execProcess) Wait() {
	<-e.waitBlock
}

func (e *execProcess) ID() string {
	return e.id
}

func (e *execProcess) Pid() int {
	e.mu.Lock()
	defer e.mu.Unlock()
	return e.pid
}

func (e *execProcess) ExitStatus() int {
	e.mu.Lock()
	defer e.mu.Unlock()
	return e.status
}

func (e *execProcess) ExitedAt() time.Time {
	e.mu.Lock()
	defer e.mu.Unlock()
	return e.exited
}

func (e *execProcess) setExited(status int) {
	e.status = status
	e.exited = time.Now()
	e.parent.platform.shutdownConsole(context.Background(), e.console)
	close(e.waitBlock)
}

func (e *execProcess) delete(ctx context.Context) error {
	e.wg.Wait()
	if e.io != nil {
		for _, c := range e.closers {
			c.Close()
		}
		e.io.Close()
	}
	return nil
}

func (e *execProcess) resize(ws console.WinSize) error {
	if e.console == nil {
		return nil
	}
	return e.console.Resize(ws)
}

func (e *execProcess) kill(ctx context.Context, sig uint32, _ bool) error {
	pid := e.pid
	if pid != 0 {
		if err := unix.Kill(pid, syscall.Signal(sig)); err != nil {
			return errors.Wrapf(checkKillError(err), "exec kill error")
		}
	}
	return nil
}

func (e *execProcess) Stdin() io.Closer {
	return e.stdin
}

func (e *execProcess) Stdio() stdio {
	return e.stdio
}

func (e *execProcess) start(ctx context.Context) (err error) {
	var (
		socket  *runc.Socket
		pidfile = filepath.Join(e.path, fmt.Sprintf("%s.pid", e.id))
	)
	if e.stdio.terminal {
		if socket, err = runc.NewTempConsoleSocket(); err != nil {
			return errors.Wrap(err, "failed to create runc console socket")
		}
		defer socket.Close()
	} else if e.stdio.isNull() {
		if e.io, err = runc.NewNullIO(); err != nil {
			return errors.Wrap(err, "creating new NULL IO")
		}
	} else {
		if e.io, err = runc.NewPipeIO(e.parent.IoUID, e.parent.IoGID); err != nil {
			return errors.Wrap(err, "failed to create runc io pipes")
		}
	}
	opts := &runc.ExecOpts{
		PidFile: pidfile,
		IO:      e.io,
		Detach:  true,
	}
	if socket != nil {
		opts.ConsoleSocket = socket
	}
	if err := e.parent.runtime.Exec(ctx, e.parent.id, e.spec, opts); err != nil {
		return e.parent.runtimeError(err, "OCI runtime exec failed")
	}
	if e.stdio.stdin != "" {
		sc, err := fifo.OpenFifo(ctx, e.stdio.stdin, syscall.O_WRONLY|syscall.O_NONBLOCK, 0)
		if err != nil {
			return errors.Wrapf(err, "failed to open stdin fifo %s", e.stdio.stdin)
		}
		e.closers = append(e.closers, sc)
		e.stdin = sc
	}
	var copyWaitGroup sync.WaitGroup
	if socket != nil {
		console, err := socket.ReceiveMaster()
		if err != nil {
			return errors.Wrap(err, "failed to retrieve console master")
		}
		if e.console, err = e.parent.platform.copyConsole(ctx, console, e.stdio.stdin, e.stdio.stdout, e.stdio.stderr, &e.wg, &copyWaitGroup); err != nil {
			return errors.Wrap(err, "failed to start console copy")
		}
	} else if !e.stdio.isNull() {
		if err := copyPipes(ctx, e.io, e.stdio.stdin, e.stdio.stdout, e.stdio.stderr, &e.wg, &copyWaitGroup); err != nil {
			return errors.Wrap(err, "failed to start io pipe copy")
		}
	}
	copyWaitGroup.Wait()
	pid, err := runc.ReadPidFile(opts.PidFile)
	if err != nil {
		return errors.Wrap(err, "failed to retrieve OCI runtime exec pid")
	}
	e.pid = pid
	return nil
}

func (e *execProcess) Status(ctx context.Context) (string, error) {
	s, err := e.parent.Status(ctx)
	if err != nil {
		return "", err
	}
	// if the container as a whole is in the pausing/paused state, so are all
	// other processes inside the container, use container state here
	switch s {
	case "paused", "pausing":
		return s, nil
	}
	e.mu.Lock()
	defer e.mu.Unlock()
	// if we don't have a pid then the exec process has just been created
	if e.pid == 0 {
		return "created", nil
	}
	// if we have a pid and it can be signaled, the process is running
	if err := unix.Kill(e.pid, 0); err == nil {
		return "running", nil
	}
	// else if we have a pid but it can nolonger be signaled, it has stopped
	return "stopped", nil
}


text:
How to setup and get the best results with Xthins
==========================================================

1. Turning Thinblocks ON/OFF
---------------------------------

When you run a Bitcoin Unimited node the XTHIN service is turned on by default.  If you wish to turn it off for some reason
you can use the bitcoin.conf setting (0 = off, 1 = on) as follows:

	use-thinblocks=0

2. Using addnode
----------------

Due to the low numbers of nodes that support XTHIN blocks, initially it is a good idea to find a node which is XTHIN capable and
force a connection using either -addnode or -connect-thinblock.

Using `addnode` is the recommended way of connecting and can be made by a simple config entry.

	addnode=<ip:port>

You can have muliple addnode entries up to a maximum of 8 connections, so you might have a config file looking as follows:

	addnode=10.233.34.33:8333
	addnode=11.222.34.55:10500
	addnode=45.33.223.34
	addnode=45.33.233.45:8333

When you use `addnode` your peer upon receiving a new block announcement by an INV message will begin a 10 second timer.  If an INV
message is not received within that 10 seconds from an XTHIN capabable node then a request for a full block will be sent out. If it
does receive an INV within the 10 second period then an XTHIN block will be requested.  This process is used as a way to bring a
full block into the BU XTHIN capable network of nodes such that once a peer does get a full block it will then very quickly propagate
a XTHIN to every other peer in the XTHIN capable network.  In such a way we avoid potentially splitting the newtwork while at
the same time maximizing our use of XTHIN technology.

3. When to use connect-thinblock
--------------------------------

the `connect-thinblock` feature is mainly used for the purpose of testing, however in some cases it can be useful for very bandwidth
constrained nodes that *always* want every downloaded block to be an XTHIN.  In such a case you would substitute the addednode entry
above with a connect-thinblockentry.  As with addnode you can have up to 8 `connect-thinblock` entries and your entry would be as
follows:

	connect-thinblock=<ip:port>

One thing to keep in mind is that with `connect-thinblock`, if the nodes that you are connecting to are down or can not service you then
you have the possiblity of not receiving any new blocks until those nodes come back on line.  Therefore use `connect-thinblock` with
caution and always use the full 8 connections if you are unsure whether the peers will be online or not.

4. The thinblock mempool limiter
---------------------------------

In order to keep the size of the XTHIN bloom filters from getting too large, a way to limit the size of mempools was implemented in v11.2
using a simple rate limiting technique.  If the size of the mempool grows to 3X the size of the largest block seen then two things happen,
the -minrelaytxfee is gradually increased until it reaches the -maxlimitertxfee, and at the same time the -limitfreerelay is gradually
reduced from 150KB per 10 minute interval down to 15KB per 10 minute.  What this system allow us to do is generally allow more zero fee
transactions through the system, yet as the mempool becomes overfull we start to choke off the free transactions while at the same time
still allowing all high priority and coinbase spends through. This mempool limiting technique has shown itself to be a great way of reducing
outbound bandwidth and preventing the propagation of transactions that will never be mined within the default 72 hour window.

During the release of v12.1, Bloom Filter targeting was introduced which supersedes the need for the mempool limiter in keeping bloom
filters smaller however it is still a valuable tool in reducing the total amount of outbound bandwidth.

There are two setting one can change as follows:

	maxlimitertxfee : default is 3 satoshi/byte
	minlimitertxfee : default is 0 satoshi/byte

Generally you can just use the defaults, but if you know for instance that an attacker is sending many transaction that are 1.014 sat/byte then you
could set your maxlimitertxfee=1.1 which would effectively choke off the attackers transactions while having the least impact to other transactions
that are likely to be mineable.

	maxlimitertxfee=1.1
	minlimitertxfee=0


text:
var fs = require('fs'),
    path = require('path'),
    xml2js = require('xml2js'),
    parser = new xml2js.Parser();

// older nodes
function parseXML(o) {
  var buffer = [];
  function process(internal_object) {
    if(typeof internal_object !== 'string' && !(internal_object instanceof String)){
      for(key in internal_object) {
        value = internal_object[key];
        if (key ==="$") {
          if (value.id) {
            buffer.push("#" + value.id);
          }
          if (value.class) {
            buffer = buffer.concat(value.class.split(" ").map(function(o) { return "." + o;}));
          }
        } else if (key !== "_") {
          buffer = buffer.concat(parseXML(value));
        }
      }
    }
  }
  if (o instanceof Array) {
    o.forEach(function(i) {
      process(i);
    });
  } else {
    process(o);
  }
  return buffer;
}

function parseXMLAndFormat(data, custom_filter) {
  var raw = parseXML(data);
  return raw
       .filter(function(elem, pos) {
          return raw.indexOf(elem) === pos && (custom_filter ? custom_filter(elem) : true);
       })
       .sort()
       .map(function(e) {
         return '"'+e+'" : {\n  \n}';
       }).join('\n');
}

function parseTSS(data) {
  var buffer = [];
  // collect existing classses and ids
  var match, regex = /^["']([\.#].+?)['"'][.\n]*?/gm;
  while (match = regex.exec(data)) {
    buffer.push(match[1]);
  }
  return buffer;
}

exports.convertString=function(string, callback) {
  parser.parseString(string, function(err,data) {
    callback(err, parseXMLAndFormat(data));
  });
};

exports.convertFile=function(file,callback) {
  fs.readFile(file, function(err, data) {
    exports.convertString(data,callback);
  });
};

exports.updateFile=function(source, target, callback) {
  var existing =[], content = "";
  if (fs.existsSync(target)) {
    content = fs.readFileSync(target);
    existing = parseTSS(content);
  }
  parser.parseString(fs.readFileSync(source), function(err, data) {
    var additional_content = parseXMLAndFormat(data, function(elem) {
      return existing.indexOf(elem) == -1;
    });
    if (additional_content.length > 0 ) {
      fs.writeFileSync(target, content + "\n" + additional_content);
      callback(null, target + " updated");
    } else {
      callback(target + " already upto date", null);
    }
  });
};


text:
class CreateShippingRates < ActiveRecord::Migration
  def self.up
    create_table :shipping_rates do |t|
      t.column :shipping_category_id, :integer
      t.column :shipping_method_id, :integer
    end
  end

  def self.down
    drop_table :shipping_rates
  end
end


text:
namespace Google.Cloud.DataCatalog.V1.Snippets
{
    // [START datacatalog_v1_generated_PolicyTagManager_GetPolicyTag_sync_flattened_resourceNames]
    using Google.Cloud.DataCatalog.V1;

    public sealed partial class GeneratedPolicyTagManagerClientSnippets
    {
        /// <summary>Snippet for GetPolicyTag</summary>
        /// <remarks>
        /// This snippet has been automatically generated and should be regarded as a code template only.
        /// It will require modifications to work:
        /// - It may require correct/in-range values for request initialization.
        /// - It may require specifying regional endpoints when creating the service client as shown in
        ///   https://cloud.google.com/dotnet/docs/reference/help/client-configuration#endpoint.
        /// </remarks>
        public void GetPolicyTagResourceNames()
        {
            // Create client
            PolicyTagManagerClient policyTagManagerClient = PolicyTagManagerClient.Create();
            // Initialize request argument(s)
            PolicyTagName name = PolicyTagName.FromProjectLocationTaxonomyPolicyTag("[PROJECT]", "[LOCATION]", "[TAXONOMY]", "[POLICY_TAG]");
            // Make the request
            PolicyTag response = policyTagManagerClient.GetPolicyTag(name);
        }
    }
    // [END datacatalog_v1_generated_PolicyTagManager_GetPolicyTag_sync_flattened_resourceNames]
}


text:
jest.autoMockOff();

var CoreManager = require('../CoreManager');
var ParsePromise = require('../ParsePromise');
var RESTController = require('../RESTController');
var asyncHelper = require('./test_helpers/asyncHelper');
var mockXHR = require('./test_helpers/mockXHR');

CoreManager.setInstallationController({
  currentInstallationId() {
    return ParsePromise.as('iid');
  }
});
CoreManager.set('APPLICATION_ID', 'A');
CoreManager.set('JAVASCRIPT_KEY', 'B');
CoreManager.set('VERSION', 'V');

describe('RESTController', () => {
  it('throws if there is no XHR implementation', () => {
    RESTController._setXHR(null);
    expect(RESTController.ajax.bind(null, 'GET', 'users/me', {})).toThrow(
      'Cannot make a request: No definition of XMLHttpRequest was found.'
    );
  });

  it('opens a XHR with the correct verb and headers', () => {
    var xhr = {
      setRequestHeader: jest.genMockFn(),
      open: jest.genMockFn(),
      send: jest.genMockFn()
    };
    RESTController._setXHR(function() { return xhr; });
    RESTController.ajax('GET', 'users/me', {}, { 'X-Parse-Session-Token': '123' });
    expect(xhr.setRequestHeader.mock.calls[0]).toEqual(
      [ 'X-Parse-Session-Token', '123' ]
    );
    expect(xhr.open.mock.calls[0]).toEqual([ 'GET', 'users/me', true ]);
    expect(xhr.send.mock.calls[0][0]).toEqual({});
  });

  it('resolves with the result of the AJAX request', asyncHelper((done) => {
    RESTController._setXHR(mockXHR([{ status: 200, response: { success: true }}]));
    RESTController.ajax('POST', 'users', {}).then((response, status, xhr) => {
      expect(response).toEqual({ success: true });
      expect(status).toBe(200);
      done();
    });
  }));

  it('retries on 5XX errors', asyncHelper((done) => {
    RESTController._setXHR(mockXHR([
      { status: 500 },
      { status: 500 },
      { status: 200, response: { success: true }}
    ]));
    RESTController.ajax('POST', 'users', {}).then((response, status, xhr) => {
      expect(response).toEqual({ success: true });
      expect(status).toBe(200);
      done();
    });
    jest.runAllTimers();
  }));

  it('aborts after too many failures', asyncHelper((done) => {
    RESTController._setXHR(mockXHR([
      { status: 500 },
      { status: 500 },
      { status: 500 },
      { status: 500 },
      { status: 500 },
      { status: 200, response: { success: true }}
    ]));
    RESTController.ajax('POST', 'users', {}).then(null, (xhr) => {
      expect(xhr).not.toBe(undefined);
      done();
    });
    jest.runAllTimers();
  }));

  it('rejects 1XX status codes', asyncHelper((done) => {
    RESTController._setXHR(mockXHR([{ status: 100 }]));
    RESTController.ajax('POST', 'users', {}).then(null, (xhr) => {
      expect(xhr).not.toBe(undefined);
      done();
    });
    jest.runAllTimers();
  }));

  it('can make formal JSON requests', () => {
    var xhr = {
      setRequestHeader: jest.genMockFn(),
      open: jest.genMockFn(),
      send: jest.genMockFn()
    };
    RESTController._setXHR(function() { return xhr; });
    RESTController.request('GET', 'classes/MyObject', {}, { sessionToken: '1234' });
    expect(xhr.open.mock.calls[0]).toEqual(
      ['POST', 'https://api.parse.com/1/classes/MyObject', true]
    );
    expect(JSON.parse(xhr.send.mock.calls[0][0])).toEqual({
      _method: 'GET',
      _ApplicationId: 'A',
      _JavaScriptKey: 'B',
      _ClientVersion: 'jsV',
      _InstallationId: 'iid',
      _SessionToken: '1234',
    });
  });

  it('handles request errors', asyncHelper((done) => {
    RESTController._setXHR(mockXHR([{
      status: 400, response: {
        code: -1,
        error: 'Something bad'
      }
    }]));
    RESTController.request('GET', 'classes/MyObject', {}, {})
      .then(null, (error) => {
        expect(error.code).toBe(-1);
        expect(error.message).toBe('Something bad');
        done();
      });
  }));
});


text:
<?php

  define('MODULE_BOXES_MANUFACTURER_INFO_TITLE', 'Manufacturer Info');
  define('MODULE_BOXES_MANUFACTURER_INFO_DESCRIPTION', 'Show manufacturer information on the product information page');
  define('MODULE_BOXES_MANUFACTURER_INFO_BOX_TITLE', 'Manufacturer Info');
  define('MODULE_BOXES_MANUFACTURER_INFO_BOX_HOMEPAGE', '%s Homepage');
  define('MODULE_BOXES_MANUFACTURER_INFO_BOX_OTHER_PRODUCTS', 'Other products');
?>


text:
<!--
Aspect which adds ARIA roles for lists and list items.

@element basic-accessible-list
-->

<link rel="import" href="../basic-aspect/basic-aspect.html">
<link rel="import" href="../basic-shared/basic-shared.html">

<script>
(function() {

// Used to assign unique IDs to item elements without IDs.
idCount = 0;

window.Basic = window.Basic || {};

window.Basic.AccessibleList = {

  contribute: {

    applySelection: function(item, selected) {
      item.setAttribute('aria-selected', selected);

      var itemId = item.getAttribute('id');
      if (itemId) {
        this.collective.outermostAttached.setAttribute('aria-activedescendant', itemId);
      }
    },

    // Ensure the outermost aspect has role="listbox".
    collectiveChanged: function() {

      var outermost = this.collective.outermostAttached;
      if (this._previousOutermostAspect === outermost) {
        // Already configured.
        return;
      }

      if (this._previousOutermostAspect) {
        // Remove ARIA attributes from previous outermost aspect.
        this._previousOutermostAspect.removeAttribute('role');
        this._previousOutermostAspect.removeAttribute('aria-activedescendant');
      }

      outermost.setAttribute('role', 'listbox');

      // Determine a base item ID based on this component's host's own ID. This
      // will be combined with a unique integer to assign IDs to items that don't
      // have an explicit ID. If the basic-list-box has ID "foo", then its items
      // will have IDs that look like "_fooOption1". If the list has no ID itself,
      // its items will get IDs that look like "_option1". Item IDs are prefixed
      // with an underscore to differentiate them from manually-assigned IDs, and
      // to minimize the potential for ID conflicts.

      // TODO: This check now comes too late for components like basic-list-box.
      // We may need to dynamically update the item IDs whenever the collection
      // changes, although that requires keeping track of whether we've changed
      // an item's ID or whether it's always had that ID.
      var elementId = outermost.getAttribute( "id" );
      this.itemBaseId = elementId ?
          "_" + elementId + "Option" :
          "_option";

      this._previousOutermostAspect = outermost;
    },

    itemAdded: function(item) {
      item.setAttribute('role', 'option');

      // Ensure each item has an ID so we can set aria-activedescendant on the
      // overall list whenever the selection changes.
      if (!item.getAttribute('id')) {
        item.setAttribute('id', this.itemBaseId + idCount++);
      }
    },

    // Catch the case where the selection is removed.
    set selectedItem(selectedItem) {
      if (selectedItem == null) {
        this.collective.outermostAttached.removeAttribute('aria-activedescendant');
      }
    }

  },

  name: 'AccessibleList',

  _previousOutermostAspect: null

};

Polymer({

  aspects: [Basic.AccessibleList],

  behaviors: [Basic.Aspect],

  is: 'basic-accessible-list'

});

})();
</script>


text:
Edit Attribute Category

                    <?php echo form_open_multipart('CbeController/attrCatUpdateProcess', array('class' => 'form-horizontal')); ?>

                            Attribute Category Name

                                <input type="text" id="name" class="form-control" name="name" value="<?php echo $attribute_category_name; ?>">
                                <input type="hidden" value="<?php echo $id; ?>" id="id" name="id"/>

                                <input type="submit" class="btn btn-primary submitbtn" value="Update">

                    <?php echo form_close(); ?>


text:
require 'rails_helper'

describe 'Student users', type: :feature, js: true do
  before do
    include Devise::TestHelpers, type: :feature
    Capybara.current_driver = :selenium
    page.driver.browser.manage.window.resize_to(1920, 1080)
  end

  before :each do
    create(:cohort,
           id: 1)
    create(:course,
           id: 10001,
           title: 'Course',
           school: 'University',
           term: 'Term',
           slug: 'University/Course_(Term)',
           submitted: 1,
           listed: true,
           passcode: 'passcode',
           start: '2015-01-01'.to_date,
           end: '2020-01-01'.to_date)
    create(:user,
           id: 100,
           wiki_id: 'Professor Sage')
    create(:courses_user,
           user_id: 100,
           course_id: 10001,
           role: 1)
    create(:cohorts_course,
           cohort_id: 1,
           course_id: 10001)
    create(:user,
           id: 101,
           wiki_id: 'Classmate')
    create(:courses_user,
           id: 2,
           user_id: 101,
           course_id: 10001,
           role: 0)
    user = create(:user,
                  id: 200,
                  wiki_token: 'foo',
                  wiki_secret: 'bar')
    login_as(user, scope: :user)
  end

  describe 'logging out' do
    it 'should work' do
      visit "/courses/#{Course.first.slug}"
      expect(page).to have_content 'Log Out'
      expect(page).not_to have_content 'Login'
      find('a', text: 'Log Out').click
      expect(page).to have_content 'Login'
      expect(page).not_to have_content 'Log Out'
    end

    it 'should not cause problems if done twice' do
      visit "/courses/#{Course.first.slug}"
      find('a', text: 'Log Out').click
      sleep 1
      visit '/sign_out'
    end
  end

  describe 'enrolling and unenrolling by button' do
    it 'should join and leave a course' do
      stub_oauth_edit

      # click enroll button
      visit "/courses/#{Course.first.slug}"
      sleep 1
      first('button').click

      # enter passcode in alert popup to enroll
      prompt = page.driver.browser.switch_to.alert
      prompt.send_keys('passcode')
      prompt.accept

      visit "/courses/#{Course.first.slug}/students"
      sleep 1
      expect(first('tbody')).to have_content User.last.wiki_id

      # now unenroll
      visit "/courses/#{Course.first.slug}"
      sleep 1
      click_button 'Leave course'
      page.driver.browser.switch_to.alert.accept

      visit "/courses/#{Course.first.slug}/students"
      sleep 1
      expect(first('tbody')).not_to have_content User.last.wiki_id
    end
  end

  describe 'enrolling by url' do
    it 'should join a course' do
      stub_oauth_edit

      visit "/courses/#{Course.first.slug}/enroll/passcode"
      sleep 1
      visit "/courses/#{Course.first.slug}/students"
      sleep 1
      expect(first('tbody')).to have_content User.last.wiki_id
      # Now try enrolling again, which shouldn't cause any errors
      visit "/courses/#{Course.first.slug}/enroll/passcode"
    end

    it 'should work even if a student is not logged in' do
      OmniAuth.config.test_mode = true
      allow_any_instance_of(OmniAuth::Strategies::Mediawiki)
        .to receive(:callback_url).and_return('/users/auth/mediawiki/callback')
      OmniAuth.config.mock_auth[:mediawiki] = OmniAuth::AuthHash.new(
        provider: 'mediawiki',
        uid: '12345',
        info: { name: 'Ragesock' },
        credentials: { token: 'foo', secret: 'bar' }
      )
      stub_oauth_edit
      logout
      visit "/courses/#{Course.first.slug}/students"
      visit "/courses/#{Course.first.slug}/enroll/passcode"
      visit "/courses/#{Course.first.slug}/students"
      sleep 1
      expect(first('tbody')).to have_content 'Ragesock'
    end

    it 'should work even if a student has never logged in before' do
      OmniAuth.config.test_mode = true
      allow_any_instance_of(OmniAuth::Strategies::Mediawiki)
        .to receive(:callback_url).and_return('/users/auth/mediawiki/callback')
      OmniAuth.config.mock_auth[:mediawiki] = OmniAuth::AuthHash.new(
        provider: 'mediawiki',
        uid: '123456',
        info: { name: 'Ragesoss' },
        credentials: { token: 'foo', secret: 'bar' }
      )
      allow(Wiki).to receive(:get_user_id).and_return(234567)
      stub_oauth_edit
      logout
      visit "/courses/#{Course.first.slug}/enroll/passcode"
      visit "/courses/#{Course.first.slug}/students"
      sleep 1
      expect(first('tbody')).to have_content 'Ragesoss'
    end

    it 'should not work if user is not persisted' do
      OmniAuth.config.test_mode = true
      allow_any_instance_of(OmniAuth::Strategies::Mediawiki)
        .to receive(:callback_url).and_return('/users/auth/mediawiki/callback')
      OmniAuth.config.mock_auth[:mediawiki] = OmniAuth::AuthHash.new(
        provider: 'mediawiki',
        uid: '123456',
        info: { name: 'Ragesoss' },
        credentials: { token: 'foo', secret: 'bar' }
      )
      allow(UserImporter).to receive(:from_omniauth).and_return(build(:user, id: 2345678))
      stub_oauth_edit
      logout
      visit "/courses/#{Course.first.slug}/enroll/passcode"
      visit "/courses/#{Course.first.slug}/students"
      sleep 1
      expect(first('tbody')).not_to have_content 'Ragesoss'
    end
  end

  describe 'adding an assigned article' do
    it 'should work' do
      stub_oauth_edit
      create(:courses_user,
             course_id: 10001,
             user_id: 200,
             role: 0)
      visit "/courses/#{Course.first.slug}/students"
      sleep 3

      # Add an assigned article
      first('button.border').click
      within('#users') { first('input').set('Selfie') }
      page.all('button.border')[1].click
      page.driver.browser.switch_to.alert.accept
      sleep 1
      page.all('button.border')[0].click
      sleep 1
      expect(page.all('tr.students')[1]).to have_content 'Selfie'
      expect(first('tr.students')).not_to have_content 'Selfie'
    end
  end

  describe 'adding a reviewed article' do
    it 'should work' do
      stub_oauth_edit
      create(:courses_user,
             course_id: 10001,
             user_id: 200,
             role: 0)
      visit "/courses/#{Course.first.slug}/students"
      sleep 3

      page.all('button.border')[1].click
      within('#users') { first('input').set('Self-portrait') }
      page.all('button.border')[2].click
      page.driver.browser.switch_to.alert.accept
      page.all('button.border')[1].click
      expect(page).to have_content 'Self-portrait'
    end
  end

  describe 'removing an assigned article' do
    it 'should work' do
      stub_oauth_edit
      create(:courses_user,
             course_id: 10001,
             user_id: 200,
             role: 0)
      create(:assignment,
             article_title: 'Selfie',
             course_id: 10001,
             user_id: 200,
             role: 0)
      visit "/courses/#{Course.first.slug}/students"
      sleep 3

      # Remove the assignment
      page.all('button.border')[0].click
      page.all('button.border')[2].click
      sleep 1
      page.driver.browser.switch_to.alert.accept
      page.all('button.border')[0].click
      sleep 1
      visit "/courses/#{Course.first.slug}/students"
      sleep 1
      expect(page).not_to have_content 'Selfie'
    end
  end

  describe 'visiting the home page' do
    it 'should see their course' do
      create(:courses_user,
             course_id: 10001,
             user_id: 200,
             role: 0)
      visit '/'
      expect(page).to have_content 'Your Courses'
      expect(page)
        .not_to have_content 'You are not participating in any courses.'
    end
  end

  after do
    logout
    Capybara.use_default_driver
  end
end


text:
#pragma once

#include "get_settings/v1_3.hpp"

namespace mf {
namespace api {
/** API action path "user" */
namespace user {
/** API action "user/get_settings" */
namespace get_settings {

// Default version
using namespace v1_3;  // NOLINT

}  // namespace get_settings
}  // namespace user
}  // namespace api
}  // namespace mf


text:
package com.microsoft.windowsazure.mobileservices;

/**
 * Class for holding data that comes back from activity which was started by MobileServiceClient
 */
public class MobileServiceActivityResult {

    public MobileServiceActivityResult(boolean isLoggedIn, String errorMessage) {
        this.isLoggedIn = isLoggedIn;
        this.errorMessage = errorMessage;
    }

    /**
     * User login succeeded or not
     */
    private boolean isLoggedIn;

    /**
     * Error message
     */
    private String errorMessage;

    public boolean isLoggedIn() {
        return this.isLoggedIn;
    }

    public String getErrorMessage() {
        return this.errorMessage;
    }
}


text:
'use strict';

var extend = require('../utils/extend');
var os = require('os');
var Q = require('q');
var IonicAppLib = require('ionic-app-lib');
var ConfigXml = IonicAppLib.configXml;
var log = IonicAppLib.logging.logger;
var cordovaUtils = require('../utils/cordova');

var settings = {
  title: 'build',
  name: 'build',
  summary: 'Build (prepare + compile) an Ionic project for a given platform.\n',
  args: {
    '<PLATFORM>': '',
    '[options]': ''
  },
  options: {
    '--nohooks|-n': {
      title: 'Do not add default Ionic hooks for Cordova',
      boolean: true
    }
  },
  isProjectTask: true
};

function run(ionic, argv, rawCliArguments) {
  var appDirectory = process.cwd();
  var rawArgs = rawCliArguments.slice(0);
  var cmdName = settings.name;

  // If platform was not passed then add it to the rawArgs
  var runPlatform = argv._[1];
  if (!runPlatform) {
    runPlatform = 'ios';
    rawArgs.push(runPlatform);
  }

  if (runPlatform === 'ios' && os.platform() !== 'darwin') {
    log.error('✗ You cannot run iOS unless you are on Mac OSX.');
    return Q();
  }

  var promiseList = []
    .concat(!cordovaUtils.isPlatformInstalled(runPlatform, appDirectory) ?
      cordovaUtils.installPlatform(runPlatform) :
      [])
    .concat(!cordovaUtils.arePluginsInstalled(appDirectory) ?
      cordovaUtils.installPlugins() :
      []);

  return Q.all(promiseList).then(function() {

    // ensure the content node was set back to its original
    return ConfigXml.setConfigXml(appDirectory, {
      resetContent: true,
      errorWhenNotFound: false
    });
  })
  .then(function() {
    var optionList = cordovaUtils.filterArgumentsForCordova(cmdName, argv, rawArgs);
    return cordovaUtils.execCordovaCommand(optionList);
  })
  .catch(function(ex) {
    if (ex instanceof Error) {
      log.error(ex);
    }
  });
}

module.exports = extend(settings, {
  run: run
});


text:
UIViewControllerAdditions
=========================

Add a lot of short cut for UIViewController, specially with MBProgressHUD


text:
from __future__ import print_function, unicode_literals, absolute_import

import argparse
import imp
import os
import re

from agstools._helpers import create_argument_groups, namespace_to_dict, format_input_path, format_output_path, read_json_file
from agstools._storenamevaluepairs import StoreNameValuePairs
from ._helpers import config_to_settings

def create_gp_sddraft(toolbox, result, output = None, name = None, folder = None, leave_existing = False, settings = {}):
    import arcpy
    import arcpyext

    # CreateGPSDDraft function doesn't work with relative paths, so we make sure they are absolute
    toolbox = os.path.abspath(toolbox)

    print("Creating SD Draft for toolbox: {0}".format(toolbox))

    if output == None:
        output = "{0}.sddraft".format(os.path.splitext(toolbox)[0])
    else:
        output = os.path.abspath(output)

    if name == None:
        path_pair = os.path.splitext(toolbox)
        name = path_pair[0]
        name = re.sub('[^0-9a-zA-Z]+', '_', name)

    arcpy.CreateGPSDDraft(
        result, output, name, server_type = "ARCGIS_SERVER", copy_data_to_server = False, folder_name = folder)

    sd_draft = arcpyext.publishing.load_gp_sddraft(output)

    if not "replace_existing" in settings:
        settings["replace_existing"] = not leave_existing

    sd_draft._set_props_from_dict(settings)

    sd_draft.save()

    print("Done, SD Draft created at: {0}".format(output))

def create_parser_gp_sddraft(parser):
    parser_sddraft = parser.add_parser("gpsddraft", add_help = False,
        help = "Creates a service definition draft for a Geo-processing Service from an ArcGIS Toolbox.",
        description = "Creates a service definition draft for a Geo-processing Service from a (Python) Toolbox.",
        formatter_class = argparse.RawDescriptionHelpFormatter)
    parser_sddraft.set_defaults(func = _process_arguments, lib_func = create_gp_sddraft, _json_files = ["config"])

    group_req, group_opt, group_flags = create_argument_groups(parser_sddraft)

    group_req.add_argument("-t", "--toolbox", required = True,
        help = "Path to the Toolbox (*.tbx, *.pyt) to create the GP service from.")

    group_req.add_argument("-r", "--tool_runner", required = True,
        help = "Path to a Python script that executes the tool.  The script must provide the tool result on a 'RESULT' variable/getter in the script's namespace.  A tool result is required in order to build a GP service.")
    group_opt.add_argument("-o", "--output",
        help = "The path to save the SD Draft to. If left out, defaults to saving with the same filename/path as the \
            Toolbox (use '*.sddraft' as extension).")
    group_opt.add_argument("-n", "--name",
        help = "Name of the published service.  Defaults to the Toolbox name (spaces and periods in the name will \
            be replaced by underscores).")
    group_opt.add_argument("-f", "--folder",
        help = "The server folder to publish the service to.  If left out, defaults to the root directory.")
    group_opt.add_argument("-s", "--settings", default = {}, nargs = "*", action = StoreNameValuePairs,
        help = "Additional key/value settings (in the form 'key=value') that will be processed by the SD Draft creator.")
    group_opt.add_argument("-c", "--config",
        help = "The absolute or relative path to a JSON-encoded configuration file (see below).")

    group_flags.add_argument("-l", "--leave-existing", default = False, action = "store_true",
        help = "Prevents an existing service from being overwritten.")

    parser_sddraft.epilog = """
-------------------------
CONFIGURATION INFORMATION
-------------------------
The JSON-encoded configuration file contains one mandatory key,
'serviceSettings', which provides a mechanism for passing in all service
settings into the Service Definition Draft generation process via a single
file.

Service Settings
---------------------
The 'serviceSettings' key contains a dictionary of key/value pairs with keys
corresponding to the name of properties on the arcpy.publishing.GPSDDraft
class, and values being the data that will be applied to each property on the
class.  All values are optional, but any supplied value will supersede any value
provided by one of the command-line parameters.

Example
-------
In the below example, options that require a detailed explanation are inside
parentheses.  The parentheses should not included in the configuration, only
one of the suggested values, or data as pertaining to the explanation.

Items in square brackets indicate a list is required input.  All available
options for the list will be shown.  Any combination of the listed options
may be used, but the value must be a square-bracket array containing zero or
more options.

All options are case sensitive.

For more information on each of the settings, see the ImageSDDraft class.

{
    "serviceSettings": {
        "capabilities": ["Uploads"],
        "cluster": "clusterNameHere",
        "description": "Service description goes here.",
        "execution_type": ("Synchronous" | "Asynchronous"),
        "folder": "ExampleServices",
        "high_isolation": (true | false),
        "idle_timeout": 600,
        "instances_per_container": 4,
        "max_instances": 4,
        "max_record_count": 1000,
        "min_instances": 1,
        "name": "ServiceNameGoesHere",
        "recycle_interval": 24,
        "recycle_start_time": "23:00",
        "replace_existing": (true | false),
        "result_map_server": (true | false),
        "summary": "Map service summary goes here.",
        "show_messages": ("None" | "Error" | "Warning" | "Info"),
        "usage_timeout": 60,
        "wait_timeout": 600,
        "wps_server": {
            "abstract": "This is an example abstract.",
            "access_constraints": "This service contains sensitive business data, INTERNAL USE ONLY.",
            "address": "123 Fake St.",
            "administrative_area": "State of FooBar",
            "app_schema_prefix": "FooBar",
            "city": "Faketown",
            "contact_instructions": "Contact hours are 8am-6pm, UTC.",
            "country": "Kingdom of FooBar",
            "custom_get_capabilities": (true | false),
            "email": "email@example.com",
            "enable_transactions": (true | false),
            "enabled": (true | false),
            "facsimile": "+111 1111 1111",
            "fees": "Service is free for non-commercial use.",
            "hours_of_service": "Service operates 24/7.",
            "individual_name": "Doe",
            "keyword": "FooBar, Spatial",
            "keywords_type": "Type Info",
            "name": "FooBarService",
            "organization": "Fake Corp.",
            "path_to_custom_get_capabilities_files": "http://foobar.com/services/Wfs/Roads",
            "phone": "+222 2222 2222",
            "position_name": "WMS Services Contact Officer",
            "post_code": 10532,
            "profile": "WPS profile",
            "provider_site": "http://www.foobar.com/",
            "role": "role info",
            "service_type": "WPS",
            "service_type_version": "1.1.0",
            "title": "FooBar Roads Service"
        }
    }
}
"""

def get_tool_runner_result(tool_runner_path):
    tool_runner_full_path = os.path.abspath(tool_runner_path)
    tool_runner_working_dir = os.path.dirname(tool_runner_full_path)
    orig_working_dir = os.getcwd()

    # Python tool runner will probably use relative imports
    # Working directory may not be the same though, so set working directory to compensate
    os.chdir(tool_runner_working_dir)

    try:
        # Turn tool runner script into result argument
        tool_runner = imp.load_source("gptoolrunner", tool_runner_full_path)
        return tool_runner.RESULT
    finally:
        # Set working directory back to original, for consistency
        os.chdir(orig_working_dir)

def _process_arguments(args):
    args, func = namespace_to_dict(args)

    args["result"] = get_tool_runner_result(args["tool_runner"])
    args.pop("tool_runner")

    args = config_to_settings(args)

    func(**args)


text: export { default } from 'ember-bulma/components/bulma-select';


text:
#ifndef CATCHERNETWORK_H_
#define CATCHERNETWORK_H_

#include <qobject.h>
#include <qnetworkreply.h>
#include <qbytearray.h>
#include <qdebug.h>
#include "talk/base/logging.h"

class CatcherNetwork: public QObject
{
Q_OBJECT

public:
	CatcherNetwork(QObject * parent = 0);
	CatcherNetwork(QByteArray *message,QObject * parent);
	virtual ~CatcherNetwork();

public slots:
	void slotFinished(QNetworkReply * reply);
	void slotError(QNetworkReply::NetworkError e);

private:
	QByteArray *_message;
};

#endif /* CatcherNetwork_H_ */


text:
const maxXS = 320
const maxSM = 767
const maxMD = 1023

export const bpMaxXS = `@media (max-width: ${maxXS}px)`
export const bpMaxSM = `@media (max-width: ${maxSM}px)`
export const bpMaxMD = `@media (max-width: ${maxMD}px)`

export const bpTabletOnly = `@media (min-width: ${
  maxSM + 1
}px) and (max-width: ${maxMD}px)`
export const bpDesktopOnly = `@media (min-width: ${maxMD + 1}px)`


text:
import json
import uuid

from django import forms
from django.template import loader

class DropzoneInput(forms.TextInput):
    template_name = 'dropzone/dropzone.html'

    class Media:
        js = ("js/dropzone/dropzone.js", "js/dropzone/django-dropzone.js",)
        css = {"all": ("css/dropzone/basic.css", "css/dropzone/dropzone.css", "css/dropzone/django-dropzone.css",)}

    def __init__(self, *args, **kwargs):
        self.dropzone_config = kwargs.pop("dropzone_config", {})
        self.uid = uuid.uuid4()
        super(DropzoneInput, self).__init__(*args, **kwargs)

    def render(self, name, value, attrs=None):
        if value is None:
            value = ''

        c = {
            "dropzone_config_json": json.dumps(self.dropzone_config),
            "name": name,
            "value": value,
            "uid": self.uid
        }

        t = loader.get_template(self.template_name)

        return t.render(c)


text:
package com.google.security.zynamics.binnavi.disassembly;

import com.google.security.zynamics.binnavi.Gui.GraphWindows.CommentDialogs.Interfaces.IComment;
import com.google.security.zynamics.zylib.disassembly.IInstruction;

import java.util.List;

/**
 * Interface that must be implemented by all classes that want to be notified about changes in an
 * instruction.
 */
public interface IInstructionListener {
  /**
   * Invoked whenever a comment is appended to the list of instruction comments.
   *
   * @param instruction The instruction where the comment is added.
   * @param comment The comment which is added.
   */
  void appendedComment(IInstruction instruction, IComment comment);

  /**
   * Invoked whenever a comment is deleted from the list of instruction comments.
   *
   * @param instruction The instruction where the comment is deleted.
   * @param comment The comment which is deleted.
   */
  void deletedComment(IInstruction instruction, IComment comment);

  /**
   * Called whenever the comment of an instruction was edited.
   *
   * @param instruction The instruction whose comment changed.
   * @param comment The changed comment of the instruction.
   */
  void editedComment(IInstruction instruction, IComment comment);

  /**
   * Invoked whenever the comments of an instruction are initialized.
   *
   * @param instruction The instruction whose comments are initialized.
   * @param comment The comments.
   */
  void initializedComment(IInstruction instruction, List<IComment> comment);
}


text:
// Copyright (c) 2012 Ecma International.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/*---
es5id: 15.4.4.15-5-9
description: >
    Array.prototype.lastIndexOf - value of 'fromIndex' is a number
    (value is -0)
---*/

assert.sameValue([0, true].lastIndexOf(true, -0), -1, '[0, true].lastIndexOf(true, -0)');
assert.sameValue([true, 0].lastIndexOf(true, -0), 0, '[true, 0].lastIndexOf(true, -0)');


text:
/**
 * \file
 *         TSCH configuration
 * \author
 *         Simon Duquennoy <simonduq@sics.se>
 */

#ifndef __TSCH_CONF_H__
#define __TSCH_CONF_H__

/********** Includes **********/

#include "contiki.h"

/******** Configuration *******/

/* Default IEEE 802.15.4e hopping sequences, obtained from https://gist.github.com/twatteyne/2e22ee3c1a802b685695 */
/* 16 channels, sequence length 16 */
#define TSCH_HOPPING_SEQUENCE_16_16 (uint8_t[]){ 16, 17, 23, 18, 26, 15, 25, 22, 19, 11, 12, 13, 24, 14, 20, 21 }
/* 4 channels, sequence length 16 */
#define TSCH_HOPPING_SEQUENCE_4_16 (uint8_t[]){ 20, 26, 25, 26, 15, 15, 25, 20, 26, 15, 26, 25, 20, 15, 20, 25 }
/* 4 channels, sequence length 4 */
#define TSCH_HOPPING_SEQUENCE_4_4 (uint8_t[]){ 15, 25, 26, 20 }
/* 2 channels, sequence length 2 */
#define TSCH_HOPPING_SEQUENCE_2_2 (uint8_t[]){ 20, 25 }
/* 1 channel, sequence length 1 */
#define TSCH_HOPPING_SEQUENCE_1_1 (uint8_t[]){ 20 }

/* Default hopping sequence, used in case hopping sequence ID == 0 */
#ifdef TSCH_CONF_DEFAULT_HOPPING_SEQUENCE
#define TSCH_DEFAULT_HOPPING_SEQUENCE TSCH_CONF_DEFAULT_HOPPING_SEQUENCE
#else
#define TSCH_DEFAULT_HOPPING_SEQUENCE TSCH_HOPPING_SEQUENCE_4_4
#endif

/* Hopping sequence used for joining (scan channels) */
#ifdef TSCH_CONF_JOIN_HOPPING_SEQUENCE
#define TSCH_JOIN_HOPPING_SEQUENCE TSCH_CONF_JOIN_HOPPING_SEQUENCE
#else
#define TSCH_JOIN_HOPPING_SEQUENCE TSCH_DEFAULT_HOPPING_SEQUENCE
#endif

/* Maximum length of the TSCH channel hopping sequence. Must be greater or
 * equal to the length of TSCH_DEFAULT_HOPPING_SEQUENCE. */
#ifdef TSCH_CONF_HOPPING_SEQUENCE_MAX_LEN
#define TSCH_HOPPING_SEQUENCE_MAX_LEN TSCH_CONF_HOPPING_SEQUENCE_MAX_LEN
#else
#define TSCH_HOPPING_SEQUENCE_MAX_LEN 16
#endif

/* Timeslot timing */

#ifndef TSCH_CONF_DEFAULT_TIMESLOT_LENGTH
#define TSCH_CONF_DEFAULT_TIMESLOT_LENGTH 10000
#endif /* TSCH_CONF_DEFAULT_TIMESLOT_LENGTH */

/* Configurable Rx guard time is micro-seconds */
#ifndef TSCH_CONF_RX_WAIT
#define TSCH_CONF_RX_WAIT 2200
#endif /* TSCH_CONF_RX_WAIT */

/* The default timeslot timing in the standard is a guard time of
 * 2200 us, a Tx offset of 2120 us and a Rx offset of 1120 us.
 * As a result, the listening device has a guard time not centered
 * on the expected Tx time. This is to be fixed in the next iteration
 * of the standard. This can be enabled with:
 * #define TSCH_DEFAULT_TS_TX_OFFSET          2120
 * #define TSCH_DEFAULT_TS_RX_OFFSET          1120
 * #define TSCH_DEFAULT_TS_RX_WAIT            2200
 *
 * Instead, we align the Rx guard time on expected Tx time. The Rx
 * guard time is user-configurable with TSCH_CONF_RX_WAIT.

 * (TS_TX_OFFSET - (TS_RX_WAIT / 2)) instead */

#if TSCH_CONF_DEFAULT_TIMESLOT_LENGTH == 10000
/* Default timeslot timing as per IEEE 802.15.4e */

#define TSCH_DEFAULT_TS_CCA_OFFSET         1800
#define TSCH_DEFAULT_TS_CCA                128
#define TSCH_DEFAULT_TS_TX_OFFSET          2120
#define TSCH_DEFAULT_TS_RX_OFFSET          (TSCH_DEFAULT_TS_TX_OFFSET - (TSCH_CONF_RX_WAIT / 2))
#define TSCH_DEFAULT_TS_RX_ACK_DELAY       800
#define TSCH_DEFAULT_TS_TX_ACK_DELAY       1000
#define TSCH_DEFAULT_TS_RX_WAIT            TSCH_CONF_RX_WAIT
#define TSCH_DEFAULT_TS_ACK_WAIT           400
#define TSCH_DEFAULT_TS_RX_TX              192
#define TSCH_DEFAULT_TS_MAX_ACK            2400
#define TSCH_DEFAULT_TS_MAX_TX             4256
#define TSCH_DEFAULT_TS_TIMESLOT_LENGTH    10000

#elif TSCH_CONF_DEFAULT_TIMESLOT_LENGTH == 15000
/* Default timeslot timing for platforms requiring 15ms slots */

#define TSCH_DEFAULT_TS_CCA_OFFSET         1800
#define TSCH_DEFAULT_TS_CCA                128
#define TSCH_DEFAULT_TS_TX_OFFSET          4000
#define TSCH_DEFAULT_TS_RX_OFFSET          (TSCH_DEFAULT_TS_TX_OFFSET - (TSCH_CONF_RX_WAIT / 2))
#define TSCH_DEFAULT_TS_RX_ACK_DELAY       3600
#define TSCH_DEFAULT_TS_TX_ACK_DELAY       4000
#define TSCH_DEFAULT_TS_RX_WAIT            TSCH_CONF_RX_WAIT
#define TSCH_DEFAULT_TS_ACK_WAIT           800
#define TSCH_DEFAULT_TS_RX_TX              2072
#define TSCH_DEFAULT_TS_MAX_ACK            2400
#define TSCH_DEFAULT_TS_MAX_TX             4256
#define TSCH_DEFAULT_TS_TIMESLOT_LENGTH    15000

#elif TSCH_CONF_DEFAULT_TIMESLOT_LENGTH == 65000U
/* 65ms timeslot, i.e. nearly the max length allowed by standard (16-bit unsigned in micro-seconds).
 * Useful for running link-layer security on sky or z1 in Cooja, where only S/W security is supported.
 * Note: this slot timing would require a total of 120ms. If a slot overlaps with the next active slot,
 * the latter will be skipped.
 * This configuration is mostly a work-around to test link-layer security in Cooja, it is recommended
 * to use it with a 6TiSCH minimal schedule of length >= 2. */

#define TSCH_DEFAULT_TS_CCA_OFFSET         1800
#define TSCH_DEFAULT_TS_CCA                128
#define TSCH_DEFAULT_TS_TX_OFFSET          52000
#define TSCH_DEFAULT_TS_RX_OFFSET          (TSCH_DEFAULT_TS_TX_OFFSET - (TSCH_CONF_RX_WAIT / 2))
#define TSCH_DEFAULT_TS_RX_ACK_DELAY       58600
#define TSCH_DEFAULT_TS_TX_ACK_DELAY       59000
#define TSCH_DEFAULT_TS_RX_WAIT            TSCH_CONF_RX_WAIT
#define TSCH_DEFAULT_TS_ACK_WAIT           800
#define TSCH_DEFAULT_TS_RX_TX              2072
#define TSCH_DEFAULT_TS_MAX_ACK            2400
#define TSCH_DEFAULT_TS_MAX_TX             4256
#define TSCH_DEFAULT_TS_TIMESLOT_LENGTH    65000

#else
#error "TSCH: Unsupported default timeslot length"
#endif

/* A custom feature allowing upper layers to assign packets to
 * a specific slotframe and link */
#ifdef TSCH_CONF_WITH_LINK_SELECTOR
#define TSCH_WITH_LINK_SELECTOR TSCH_CONF_WITH_LINK_SELECTOR
#else /* TSCH_CONF_WITH_LINK_SELECTOR */
#define TSCH_WITH_LINK_SELECTOR 0
#endif /* TSCH_CONF_WITH_LINK_SELECTOR */

/* Estimate the drift of the time-source neighbor and compensate for it? */
#ifdef TSCH_CONF_ADAPTIVE_TIMESYNC
#define TSCH_ADAPTIVE_TIMESYNC TSCH_CONF_ADAPTIVE_TIMESYNC
#else
#define TSCH_ADAPTIVE_TIMESYNC 1
#endif

/* HW frame filtering enabled */
#ifdef TSCH_CONF_HW_FRAME_FILTERING
#define TSCH_HW_FRAME_FILTERING TSCH_CONF_HW_FRAME_FILTERING
#else /* TSCH_CONF_HW_FRAME_FILTERING */
#define TSCH_HW_FRAME_FILTERING 1
#endif /* TSCH_CONF_HW_FRAME_FILTERING */

/* Keep radio always on within TSCH timeslot (1) or turn it off between packet and ACK? (0) */
#ifdef TSCH_CONF_RADIO_ON_DURING_TIMESLOT
#define TSCH_RADIO_ON_DURING_TIMESLOT TSCH_CONF_RADIO_ON_DURING_TIMESLOT
#else
#define TSCH_RADIO_ON_DURING_TIMESLOT 0
#endif

/* How long to scan each channel in the scanning phase */
#ifdef TSCH_CONF_CHANNEL_SCAN_DURATION
#define TSCH_CHANNEL_SCAN_DURATION TSCH_CONF_CHANNEL_SCAN_DURATION
#else
#define TSCH_CHANNEL_SCAN_DURATION CLOCK_SECOND
#endif

#endif /* __TSCH_CONF_H__ */


text:
using UnityEngine;
using System.Collections;
using PowIoC;

public class ViewControllerMediator : ScriptableObject, ISetup, IPlugin {
	[Inject(false)]
	ILogger logger;

	public void Setup () {
		logger.Context = this.GetType().ToString();
	}

	public void PreInject (object target, object field) {
		// if(logger != null) logger.Log("");
		IViewContainer container = field as IViewContainer;
		IView obj = target as IView;
		if (container != null && obj != null) {
			container.Register(obj);
		}
	}

	public void PostInject (object target, object field) {
		// if(logger != null) logger.Log("");
	}

}


text:
package chatty;

import chatty.gui.HtmlColors;
import chatty.util.settings.Settings;
import java.awt.Color;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 *
 * @author tduva
 */
public class UsercolorManager {

    private final Settings settings;
    private volatile List<UsercolorItem> data;

    public UsercolorManager(Settings settings) {
        this.settings = settings;
        loadFromSettings();
        // TEST
//        data = new ArrayList<>();
//        for (int i=0;i<10000;i++) {
//            data.add(new UsercolorItem("user"+i, Color.BLACK));
//        }
    }

    private void loadFromSettings() {
        List<String> l = new LinkedList<>();
        settings.getList("usercolors", l);
//        synchronized(settings.LOCK) {
//            List<String> settingList = settings.getList2("usercolors");
//            l.addAll(settingList);
//        }
        List<UsercolorItem> loadedData = new ArrayList<>();
        for (String entry : l) {
            int splitAt = entry.lastIndexOf(",");
            if (splitAt > 0 && entry.length() > splitAt+1) {
                String id = entry.substring(0, splitAt);
                Color color = HtmlColors.decode(entry.substring(splitAt + 1));
                loadedData.add(new UsercolorItem(id, color));
            }
        }
        data = loadedData;

//        synchronized(settingMap) {
//            Map<String, String> m = settingMap;
//            List<UsercolorItem> loadedData = new ArrayList<>();
//            for (Map.Entry<String, String> entry : m.entrySet()) {
//                String id = entry.getKey();
//                Color color = HtmlColors.decode(entry.getValue());
//                loadedData.add(new UsercolorItem(id, color));
//            }
//            data = loadedData;
//        }
    }

    /**
     * Copy the current data to the settings.
     */
    private void saveToSettings() {
        List<String> dataToSave = new LinkedList<>();
        for (UsercolorItem item : data) {
            dataToSave.add(item.getId()+","+HtmlColors.getColorString(item.getColor()));
        }
//        synchronized (settings.LOCK) {
//            List<String> settingList = settingsgetList2t("usercolors");
//            settingList.clear();
//            settingList.addAll(dataToSave);
//        }
        settings.putList("usercolors", dataToSave);
    }

    /**
     * Gets the current data.
     *
     * @return An ordered list of {@link UsercolorItem}s.
     */
    public synchronized List<UsercolorItem> getData() {
        return new ArrayList<>(data);
    }

    /**
     * Sets new data and copies it to the settings as well.
     *
     * @param newData A list of ordered {@link UsercolorItem}s.
     */
    public synchronized void setData(List<UsercolorItem> newData) {
        data = new ArrayList<>(newData);
        saveToSettings();
    }

    /**
     * Returns the color for this user, or null if no items matched this user.
     *
     * @param user
     * @return
     */
    public synchronized Color getColor(User user) {
        if (data == null || !settings.getBoolean("customUsercolors")) {
            return null;
        }
        for (UsercolorItem item : data) {
            if (item.type == UsercolorItem.TYPE_COLOR) {
                if (item.idColor.equals(user.getPlainColor())) {
                    return item.color;
                }
            } else if (item.type == UsercolorItem.TYPE_NAME) {
                if (item.id.equalsIgnoreCase(user.getNick())) {
                    return item.color;
                }
            } else if (item.type == UsercolorItem.TYPE_STATUS) {
                if (       (item.id.equals("$mod") && user.isModerator())
                        || (item.id.equals("$sub") && user.isSubscriber())
                        || (item.id.equals("$turbo") && user.hasTurbo())
                        || (item.id.equals("$admin") && user.isAdmin())
                        || (item.id.equals("$broadcaster") && user.isBroadcaster())
                        || (item.id.equals("$staff") && user.isStaff())) {
                    return item.color;
                }
            } else if (item.type == UsercolorItem.TYPE_CATEGORY) {
                if (user.hasCategory(item.category)) {
                    return item.color;
                }
            } else if (item.type == UsercolorItem.TYPE_ALL) {
                return item.color;
            }
        }
        return null;
    }

}


text:
package org.spongepowered.api.util.generator.dummy;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import org.spongepowered.api.CatalogType;

import java.lang.reflect.InvocationTargetException;

/**
 * This class dynamically generates a dummy class for a given interface (usually a {@link CatalogType}).
 *
 *
The generated class implements all of the interface's methods, but
 * throws an {@link UnsupportedOperationException} with an informative error message.

 */
public final class DummyObjectProvider {

    static final DummyClassGeneratorProvider factoryProvider = new DummyClassGeneratorProvider("org.spongepowered.api.util.dummy");

    private static final LoadingCache<Class<?>, Class<?>> factories = CacheBuilder.newBuilder().build(
            new CacheLoader<Class<?>, Class<?>>() {

                @Override
                public Class<?> load(Class<?> type) {
                    return factoryProvider.create(type, UnsupportedOperationException.class);
                }
            });

    /**
     * Creates a new dummy class implementing the specified interface
     *
     * @param type The interface to generate a dummy class for
     * @param <T> The type of class to be created
     * @return The generated dummy class
     */
    @SuppressWarnings("unchecked")
    public static <T> T createFor(Class<T> type, String fieldName) {
        try {
            return (T) factories.getUnchecked(type).getConstructor(String.class).newInstance(fieldName);
        } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
            throw new RuntimeException(String.format("Failed to instantiate dummy class for class %s", type), e);
        }
    }

    @SuppressWarnings("unchecked")
    public static <T, I extends T> I createExtendedFor(Class<T> type, String fieldName) {
        try {
            return (I) factories.getUnchecked(type).getConstructor(String.class).newInstance(fieldName);
        } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
            throw new RuntimeException(String.format("Failed to instantiate dummy class for class %s", type), e);
        }
    }

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>DeliveryAccessWS</title>
<meta name="date" content="2015-06-15">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.exlibris.dps.sdk.repository

Interface DeliveryAccessWS

All Superinterfaces:

com.exlibris.core.infra.svc.api.GenericWebService

public interface DeliveryAccessWS
extends com.exlibris.core.infra.svc.api.GenericWebService

Method Summary

Methods

Modifier and Type
Method and Description

java.lang.String
getBaseFileUrl(java.lang.String dvs)

Returns the Stream Gate file viewer base URL for the given dvs.

java.lang.String
getCMSRecord(java.lang.String dvs,
            java.lang.String iePID)

Returns the CMS DC XML of the IE.

java.lang.String
getDnxDocument(java.lang.String dvs,
              java.lang.String pid)

Returns the DNX document XML of the entity (IE/REP/FILE) that its PID is associated to the given dvs.

java.lang.String
getExtendedIEByDVS(java.lang.String dvs,
                  long flags)

Returns the IE METS document which is associated to the given dvs, including all data defined by the flags.

java.lang.String
getFilePathByDvs(java.lang.String dvs,
                java.lang.String pid)

Returns the path to a file which is associated to the given dvs.

java.lang.String
getFullIEByDVS(java.lang.String dvs)

Deprecated.

java.lang.String
getIE(java.lang.String pid)

Deprecated.

java.lang.String
getIEByDVS(java.lang.String dvs)

Deprecated.

java.lang.String
getMetadata(java.lang.String dvs,
           java.lang.String pid,
           java.lang.String mdType,
           java.lang.String mdSubType)

Returns the Metadata XML of the entity (IE/REP/FILE) that its PID is associated to the given dvs.

Methods inherited from interface com.exlibris.core.infra.svc.api.GenericWebService

getHeartBit

Method Detail

getIE

@Deprecated
java.lang.String getIE(java.lang.String pid)
                       throws java.lang.Exception

Deprecated.

Throws:

java.lang.Exception

getIEByDVS

@Deprecated
@WSDLDocumentation(value="Returns the IE METS document which is associated to the given dvs, including the IE and Representation level sections.")
java.lang.String getIEByDVS(java.lang.String dvs)
                            throws java.lang.Exception

Deprecated.

Returns the IE METS document which is associated to the given dvs, including the IE and Representation level sections.

Parameters:

dvs - The Delivery session key

Returns:

IE METS document xml

Throws:

java.lang.Exception - when the dvs is invalid

getFullIEByDVS

@Deprecated
@WSDLDocumentation(value="Returns the IE METS document which is associated to the given dvs, including the IE, Representation and File level sections.")
java.lang.String getFullIEByDVS(java.lang.String dvs)
                                throws java.lang.Exception

Deprecated.

Returns the IE METS document which is associated to the given dvs, including the IE, Representation and File level sections.

Parameters:

dvs - The Delivery session key

Returns:

IE METS document xml

Throws:

java.lang.Exception - when the dvs is invalid

getExtendedIEByDVS

@WSDLDocumentation(value="Returns the IE METS document which is associated to the given dvs, including all data defined by the flags.")
java.lang.String getExtendedIEByDVS(java.lang.String dvs,
                                                    long flags)
                                    throws java.lang.Exception

Returns the IE METS document which is associated to the given dvs, including all data defined by the flags.
 Flags can be combined in an OR bitwise operation. Example: to include all revisions without their files, send 3 (=1|2).

Parameters:

dvs - The Delivery session key

flags - The flag that defines what to include in retrieved Mets.
                        0 - Basic METS (Latest REPs, including files)
                1 - to include all revisions and not just the latest
                        2 - to exclude the files
                        4 - to include shared md - CMS

                        8 - to include shared md - AR

          16 -to exclude the files and include file size and Mime Type

Returns:

IE METS document xml

Throws:

java.lang.Exception - when the dvs is invalid

getFilePathByDvs

@WSDLDocumentation(value="Returns the path to a file which is associated to the given dvs. File path is given by the StoragePlugin#getFullFilePath(String)")
java.lang.String getFilePathByDvs(java.lang.String dvs,
                                                  java.lang.String pid)
                                  throws java.lang.Exception

Returns the path to a file which is associated to the given dvs.
 File path is given by the StoragePlugin.getFullFilePath(String).

Parameters:

dvs - The Delivery session key

pid - file PID

Returns:

file path on NFS

Throws:

java.lang.Exception

getDnxDocument

@WSDLDocumentation(value="Returns the DNX document XML of the entity (IE/REP/FILE) that its PID is associated to the given dvs.")
java.lang.String getDnxDocument(java.lang.String dvs,
                                                java.lang.String pid)
                                throws java.lang.Exception

Returns the DNX document XML of the entity (IE/REP/FILE) that its PID is associated to the given dvs.

Parameters:

dvs - The Delivery session key

pid - IE/REP/FILE PID

Returns:

DNX document XML

Throws:

java.lang.Exception

getMetadata

@WSDLDocumentation(value="Returns the Metadata XML of the entity (IE/REP/FILE) that its PID is associated to the given dvs.")
java.lang.String getMetadata(java.lang.String dvs,
                                             java.lang.String pid,
                                             java.lang.String mdType,
                                             java.lang.String mdSubType)
                             throws java.lang.Exception

Returns the Metadata XML of the entity (IE/REP/FILE) that its PID is associated to the given dvs.

Parameters:

dvs - The Delivery session key

pid - IE/REP/FILE PID

mdType - Metadata type (e.g. descriptive)

mdSubType - Metadata sub type (e.g. dc)

Returns:

Metadata XML

Throws:

java.lang.Exception

getCMSRecord

@WSDLDocumentation(value="Returns the CMS DC XML of the IE.")
java.lang.String getCMSRecord(java.lang.String dvs,
                                              java.lang.String iePID)
                              throws java.lang.Exception

Returns the CMS DC XML of the IE.

Parameters:

dvs - The Delivery session key

iePID - IE PID

Returns:

CMS DC XML

Throws:

java.lang.Exception

getBaseFileUrl

@WSDLDocumentation(value="Returns the base file URL for the given dvs. External viewers should append the file PID to the baseFileUrl in order to get the file\'s stream from Rosetta.")
java.lang.String getBaseFileUrl(java.lang.String dvs)
                                throws java.lang.Exception

Returns the Stream Gate file viewer base URL for the given dvs.
 This URL can be used by external viewers to get the files' streams.
 This method is more recommended than using the getFilePathByDvs as it doesn't expose the file path on the storage to the viewer.
 The external viewer should append the file PID to the baseFileUrl in order to get the file's stream from Rosetta.

Parameters:

dvs - The Delivery session key

Returns:

Stream Gate file viewer base URL

Throws:

java.lang.Exception

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


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

    Copyright (C) [2013] [The FURTHeR Project]

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

            http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

-->
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:osgix="http://www.springframework.org/schema/osgi-compendium"
	xmlns:ctx="http://www.springframework.org/schema/context" xmlns:osgi="http://www.springframework.org/schema/osgi"
	xsi:schemaLocation="
	http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
	http://www.springframework.org/schema/context
	http://www.springframework.org/schema/context/spring-context.xsd
	http://www.springframework.org/schema/osgi-compendium
	http://www.springframework.org/schema/osgi-compendium/spring-osgi-compendium.xsd
	http://www.springframework.org/schema/osgi
    http://www.springframework.org/schema/osgi/spring-osgi.xsd">

	<!-- =========================================== -->
	<!-- Managed properties                          -->
	<!-- =========================================== -->

	<!--
		definitions using elements of the osgi namespace can be included in
		this file. There is no requirement to keep these definitions in a
		separate file if you do not want to. The rationale for keeping these
		definitions separate is to facilitate integration testing of the
		bundle outside of an OSGi container
	-->

	<!--Encrypted placeholder configurer -->
	<import resource="classpath:META-INF/core/util/core-util-encryption-sha1.xml" />
	<bean parent="propertiesEncryptor">
		<property name="properties" ref="mdrImplProps" />
	</bean>

	<!-- Configuration Admin entry -->
	<osgix:cm-properties id="mdrImplProps"
		persistent-id="further.mdr.data">

		<prop key="datasource.name">mdr-data-datasource</prop>
		<prop key="datasource.url"></prop>
		<prop key="datasource.driver"></prop>
		<prop key="datasource.user"></prop>
		<prop key="datasource.password"></prop>
		<!--
			Note: this might not work with hbm2ddl create/update. See
			https://forum.hibernate.org/viewtopic.php?t=927555&highlight=
		-->
		<prop key="hibernate.default_schema"></prop>

		<!-- SQL implementation Hibernate dialect -->
		<prop key="hibernate.dialect"></prop>

		<!-- ################################## -->
		<!-- Hibernate configuration            -->
		<!-- ################################## -->

		<!-- ============================ -->
		<!-- Hibernate options            -->
		<!-- ============================ -->

		<!-- Turn on for SQL debugging  -->
		<prop key="hibernate.show_sql">false</prop>
		<!-- <prop key="hibernate.hbm2ddl.auto">update</prop>  -->

		<!-- ============================ -->
		<!--C3P0 connection pool config   -->
		<!-- ============================ -->

		<!--
			References for setting parameter values:
			http://www.hibernate.org/214.html
		-->
		<!-- http://forum.java.sun.com/thread.jspa?threadID=691105&tstart=0 -->
		<!-- Times are in seconds. -->
		<prop key="c3p0.initialPoolSize">5</prop>
		<prop key="c3p0.minPoolSize">5</prop>
		<prop key="c3p0.maxPoolSize">15</prop>
		<prop key="c3p0.maxStatements">50</prop>
		<prop key="c3p0.acquireRetryAttempts">30</prop>
		<prop key="c3p0.acquireIncrement">5</prop>
		<prop key="c3p0.testConnectionOnCheckin">true</prop>
		<prop key="c3p0.preferredTestQuery"></prop>
		<!--
			Timeout: [1] set it to 100, if that doesn't work, [2] set it to 10.
		-->
		<prop key="c3p0.timeout">100</prop>
		<prop key="c3p0.idleConnectionTestPeriod">150</prop>
		<prop key="c3p0.maxIdleTime">1800</prop>

	</osgix:cm-properties>

	<!-- =========================================== -->
	<!-- Imported OSGi services                      -->
	<!-- =========================================== -->

</beans>


text:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using MVC4_MobileApp.Models;

namespace MVC4_MobileApp.Controllers
{
    public class OrderController : ApiController
    {
        private jQMOrderDBEntities db = new jQMOrderDBEntities();

        // GET api/Order
        public IEnumerable<Order> GetOrders()
        {
            var orders = db.Orders.Include("Product");
            return orders.AsEnumerable();
        }

        // GET api/Order/5
        public Order GetOrder(int id)
        {
            Order order = db.Orders.Single(o => o.OrderId == id);
            if (order == null)
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
            }

            return order;
        }

        // PUT api/Order/5
        public HttpResponseMessage PutOrder(int id, Order order)
        {
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }

            if (id != order.OrderId)
            {
                return Request.CreateResponse(HttpStatusCode.BadRequest);
            }

            db.Orders.Attach(order);
            db.ObjectStateManager.ChangeObjectState(order, EntityState.Modified);

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
            }

            return Request.CreateResponse(HttpStatusCode.OK);
        }

        // POST api/Order
        public HttpResponseMessage PostOrder(Order order)
        {
            if (ModelState.IsValid)
            {
                db.Orders.AddObject(order);
                db.SaveChanges();

                HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, order);
                response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = order.OrderId }));
                return response;
            }
            else
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }
        }

        // DELETE api/Order/5
        public HttpResponseMessage DeleteOrder(int id)
        {
            Order order = db.Orders.Single(o => o.OrderId == id);
            if (order == null)
            {
                return Request.CreateResponse(HttpStatusCode.NotFound);
            }

            db.Orders.DeleteObject(order);

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
            }

            return Request.CreateResponse(HttpStatusCode.OK, order);
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}


text:
package org.folio.okapi.service.impl;

import io.vertx.core.Future;
import java.util.List;
import org.folio.okapi.bean.ModuleDescriptor;
import org.folio.okapi.service.ModuleStore;

public class ModuleStorePostgres implements ModuleStore {

  private static final String TABLE = "modules";
  private static final String JSON_COLUMN = "modulejson";
  private static final String ID_SELECT = JSON_COLUMN + "->>'id' = $1";
  private static final String ID_INDEX = JSON_COLUMN + "->'id'";
  private final PostgresTable<ModuleDescriptor> pgTable;

  public ModuleStorePostgres(PostgresHandle pg) {
    this.pgTable = new PostgresTable<>(pg, TABLE, JSON_COLUMN, ID_INDEX, ID_SELECT, "module_id");
  }

  @Override
  public Future<Void> init(boolean reset) {
    return pgTable.init(reset);
  }

  @Override
  public Future<Void> insert(List<ModuleDescriptor> mds) {
    return pgTable.insertBatch(mds);
  }

  @Override
  public Future<List<ModuleDescriptor>> getAll() {
    return pgTable.getAll(ModuleDescriptor.class);
  }

  @Override
  public Future<Boolean> delete(String id) {
    return pgTable.delete(id);
  }
}


text:
/**
 * Contains utility classes used by VisEditor to generate UI for components in EntityProperties dialogs
 * @author Kotcrab
 */
package com.kotcrab.vis.runtime.util.autotable;