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

<title>FieldEditorOverlayPage</title>
<meta name="date" content="2014-08-17">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.osate.xtext.aadl2.agcl.analysis.misc

Class FieldEditorOverlayPage

java.lang.Object

org.eclipse.jface.dialogs.DialogPage

org.eclipse.jface.preference.PreferencePage

org.eclipse.jface.preference.FieldEditorPreferencePage

org.osate.xtext.aadl2.agcl.analysis.misc.FieldEditorOverlayPage

All Implemented Interfaces:

java.util.EventListener, org.eclipse.jface.dialogs.IDialogPage, org.eclipse.jface.dialogs.IMessageProvider, org.eclipse.jface.preference.IPreferencePage, org.eclipse.jface.util.IPropertyChangeListener, org.eclipse.ui.IWorkbenchPropertyPage

Deprecated.

@Deprecated
public abstract class FieldEditorOverlayPage
extends org.eclipse.jface.preference.FieldEditorPreferencePage
implements org.eclipse.ui.IWorkbenchPropertyPage

This class implements a field-editor page that is shared between workspace and project-specific
 preferences.

 It is based on the class described in the article
 Mutatis mutandis - Using Preference Pages as Property Pages
 by Berthold Daum.

Author:

eposse

Field Summary

Fields

Modifier and Type
Field and Description

static java.lang.String
USEPROJECTSETTINGS

Deprecated.

Fields inherited from class org.eclipse.jface.preference.FieldEditorPreferencePage

FLAT, GRID

Fields inherited from interface org.eclipse.jface.dialogs.IMessageProvider

ERROR, INFORMATION, NONE, WARNING

Constructor Summary

Constructors

Constructor and Description

FieldEditorOverlayPage()

Deprecated.

FieldEditorOverlayPage(int style)

Deprecated.

FieldEditorOverlayPage(java.lang.String title,
                      org.eclipse.jface.resource.ImageDescriptor image,
                      int style)

Deprecated.

FieldEditorOverlayPage(java.lang.String title,
                      int style)

Deprecated.

Method Summary

Methods

Modifier and Type
Method and Description

void
createControl(org.eclipse.swt.widgets.Composite parent)

Deprecated.

org.eclipse.core.runtime.IAdaptable
getElement()

Deprecated.

org.eclipse.jface.preference.IPreferenceStore
getPreferenceStore()

Deprecated.

boolean
isPropertyPage()

Deprecated.

boolean
performOk()

Deprecated.

void
setElement(org.eclipse.core.runtime.IAdaptable element)

Deprecated.

Methods inherited from class org.eclipse.jface.preference.FieldEditorPreferencePage

dispose, propertyChange, setVisible

Methods inherited from class org.eclipse.jface.preference.PreferencePage

applyData, computeSize, getContainer, isValid, okToLeave, performCancel, performHelp, setContainer, setErrorMessage, setMessage, setPreferenceStore, setSize, setTitle, setValid, toString

Methods inherited from class org.eclipse.jface.dialogs.DialogPage

getControl, getDescription, getErrorMessage, getImage, getMessage, getMessageType, getShell, getTitle, setDescription, setImageDescriptor, setMessage

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, wait, wait, wait

Methods inherited from interface org.eclipse.jface.preference.IPreferencePage

computeSize, isValid, okToLeave, performCancel, setContainer, setSize

Methods inherited from interface org.eclipse.jface.dialogs.IDialogPage

dispose, getControl, getDescription, getErrorMessage, getImage, getMessage, getTitle, performHelp, setDescription, setImageDescriptor, setTitle, setVisible

Field Detail

USEPROJECTSETTINGS

public static final java.lang.String USEPROJECTSETTINGS

Deprecated.

See Also:

Constant Field Values

Constructor Detail

FieldEditorOverlayPage

public FieldEditorOverlayPage()

Deprecated.

FieldEditorOverlayPage

public FieldEditorOverlayPage(int style)

Deprecated.

Parameters:

style -

FieldEditorOverlayPage

public FieldEditorOverlayPage(java.lang.String title,
                      int style)

Deprecated.

Parameters:

title -

style -

FieldEditorOverlayPage

public FieldEditorOverlayPage(java.lang.String title,
                      org.eclipse.jface.resource.ImageDescriptor image,
                      int style)

Deprecated.

Parameters:

title -

image -

style -

Method Detail

getElement

public org.eclipse.core.runtime.IAdaptable getElement()

Deprecated.

Specified by:

getElement in interface org.eclipse.ui.IWorkbenchPropertyPage

setElement

public void setElement(org.eclipse.core.runtime.IAdaptable element)

Deprecated.

Specified by:

setElement in interface org.eclipse.ui.IWorkbenchPropertyPage

isPropertyPage

public boolean isPropertyPage()

Deprecated.

createControl

public void createControl(org.eclipse.swt.widgets.Composite parent)

Deprecated.

Specified by:

createControl in interface org.eclipse.jface.dialogs.IDialogPage

Overrides:

createControl in class org.eclipse.jface.preference.PreferencePage

getPreferenceStore

public org.eclipse.jface.preference.IPreferenceStore getPreferenceStore()

Deprecated.

Overrides:

getPreferenceStore in class org.eclipse.jface.preference.PreferencePage

performOk

public boolean performOk()

Deprecated.

Specified by:

performOk in interface org.eclipse.jface.preference.IPreferencePage

Overrides:

performOk in class org.eclipse.jface.preference.FieldEditorPreferencePage

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
package org.apache.jackrabbit.oak.plugins.blob;

import static com.google.common.collect.Sets.newHashSet;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertTrue;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import javax.annotation.Nullable;

import com.google.common.base.Function;
import com.google.common.collect.Iterables;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import junit.framework.Assert;

import org.apache.commons.io.IOUtils;
import org.apache.jackrabbit.core.data.DataIdentifier;
import org.apache.jackrabbit.core.data.DataRecord;
import org.apache.jackrabbit.core.data.DataStoreException;
import org.apache.jackrabbit.oak.commons.FileIOUtils;
import org.apache.jackrabbit.oak.plugins.blob.datastore.DataStoreBlobStore;
import org.apache.jackrabbit.oak.plugins.blob.datastore.SharedDataStoreUtils;
import org.apache.jackrabbit.oak.plugins.blob.datastore.SharedDataStoreUtils.SharedStoreRecordType;
import org.apache.jackrabbit.oak.plugins.blob.datastore.DataStoreUtils;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Test for SharedDataUtils to test addition, retrieval and deletion of root records.
 */
public class SharedDataStoreUtilsTest {
    private static final Logger log = LoggerFactory.getLogger(SharedDataStoreUtilsTest.class);

    @Rule
    public TemporaryFolder folder = new TemporaryFolder(new File("target"));

    protected DataStoreBlobStore dataStore;

    protected DataStoreBlobStore getBlobStore(File root) throws Exception {
        return DataStoreUtils.getBlobStore(root);
    }

    @Test
    public void test() throws Exception {
        File rootFolder = folder.newFolder();
        dataStore = getBlobStore(rootFolder);
        String repoId1 = UUID.randomUUID().toString();
        String repoId2 = UUID.randomUUID().toString();

        // Add repository records
        dataStore.addMetadataRecord(new ByteArrayInputStream(new byte[0]),
            SharedStoreRecordType.REPOSITORY.getNameFromId(repoId1));
        DataRecord repo1 = dataStore.getMetadataRecord(SharedStoreRecordType.REPOSITORY.getNameFromId(repoId1));
        dataStore.addMetadataRecord(new ByteArrayInputStream(new byte[0]),
            SharedStoreRecordType.REPOSITORY.getNameFromId(repoId2));
        DataRecord repo2 = dataStore.getMetadataRecord(SharedStoreRecordType.REPOSITORY.getNameFromId(repoId2));

        // Add reference marker record for repo1
        dataStore.addMetadataRecord(new ByteArrayInputStream(new byte[0]),
                                       SharedStoreRecordType.MARKED_START_MARKER.getNameFromId(repoId1));
        DataRecord markerRec1 = dataStore.getMetadataRecord(SharedStoreRecordType.MARKED_START_MARKER.getNameFromId(repoId1));
        assertEquals(
               SharedStoreRecordType.MARKED_START_MARKER.getIdFromName(markerRec1.getIdentifier().toString()),
               repoId1);
        long lastModifiedMarkerRec1 = markerRec1.getLastModified();
        TimeUnit.MILLISECONDS.sleep(100);

        // Add reference records
        dataStore.addMetadataRecord(new ByteArrayInputStream(new byte[0]),
            SharedStoreRecordType.REFERENCES.getNameFromId(repoId1));
        DataRecord rec1 = dataStore.getMetadataRecord(SharedStoreRecordType.REFERENCES.getNameFromId(repoId1));
        long lastModifiedRec1 = rec1.getLastModified();
        TimeUnit.MILLISECONDS.sleep(25);
        dataStore.addMetadataRecord(new ByteArrayInputStream(new byte[0]),
            SharedStoreRecordType.REFERENCES.getNameFromId(repoId2));
        DataRecord rec2 = dataStore.getMetadataRecord(SharedStoreRecordType.REFERENCES.getNameFromId(repoId2));
        long lastModifiedRec2 = rec2.getLastModified();

        assertEquals(SharedStoreRecordType.REPOSITORY.getIdFromName(repo1.getIdentifier().toString()), repoId1);
        assertEquals(
                SharedStoreRecordType.REPOSITORY.getIdFromName(repo2.getIdentifier().toString()),
                repoId2);
        assertEquals(
                SharedStoreRecordType.REFERENCES.getIdFromName(rec1.getIdentifier().toString()),
                repoId1);
        assertEquals(
                SharedStoreRecordType.REFERENCES.getIdFromName(rec2.getIdentifier().toString()),
                repoId2);

        // All the references from registered repositories are available
        Assert.assertTrue(SharedDataStoreUtils
                .refsNotAvailableFromRepos(dataStore.getAllMetadataRecords(SharedStoreRecordType.REPOSITORY.getType()),
                    dataStore.getAllMetadataRecords(SharedStoreRecordType.REFERENCES.getType())).isEmpty());

        // Since, we don't care about which file specifically but only the earliest timestamped record
        // Earliest time should be the min timestamp from the 2 reference files
        long minRefTime = (lastModifiedRec1 <= lastModifiedRec2 ? lastModifiedRec1 : lastModifiedRec2);
        assertEquals(
               SharedDataStoreUtils.getEarliestRecord(
                        dataStore.getAllMetadataRecords(SharedStoreRecordType.REFERENCES.getType())).getLastModified(),
                        minRefTime);

        // the marker timestamp should be the minimum
        long minMarkerTime =
            SharedDataStoreUtils.getEarliestRecord(
                    dataStore.getAllMetadataRecords(SharedStoreRecordType.MARKED_START_MARKER.getType()))
                        .getLastModified();
        Assert.assertTrue(minRefTime >= minMarkerTime);

        // Delete references and check back if deleted
        dataStore.deleteAllMetadataRecords(SharedStoreRecordType.REFERENCES.getType());
        Assert.assertTrue(dataStore.getAllMetadataRecords(SharedStoreRecordType.REFERENCES.getType()).isEmpty());

        // Delete markers and check back if deleted
        dataStore.deleteAllMetadataRecords(SharedStoreRecordType.MARKED_START_MARKER.getType());
        Assert.assertTrue(dataStore.getAllMetadataRecords(SharedStoreRecordType.MARKED_START_MARKER.getType()).isEmpty());

        // Repository ids should still be available
        assertEquals(2,
            dataStore.getAllMetadataRecords(SharedStoreRecordType.REPOSITORY.getType()).size());
    }

    @Test
    public void testAddMetadata() throws Exception {
        File rootFolder = folder.newFolder();
        dataStore = getBlobStore(rootFolder);
        String repoId = UUID.randomUUID().toString();
        Set<String> refs = Sets.newHashSet("1_1", "1_2");
        File f = folder.newFile();
        FileIOUtils.writeStrings(refs.iterator(), f, false);

        dataStore.addMetadataRecord(new FileInputStream(f),
            SharedStoreRecordType.REFERENCES.getNameFromId(repoId));
        DataRecord rec = dataStore.getMetadataRecord(SharedStoreRecordType.REFERENCES.getNameFromId(repoId));
        Set<String> refsReturned = FileIOUtils.readStringsAsSet(rec.getStream(), false);
        Assert.assertEquals(refs, refsReturned);
        dataStore.deleteAllMetadataRecords(SharedStoreRecordType.REFERENCES.getType());

        dataStore.addMetadataRecord(f,
            SharedStoreRecordType.REFERENCES.getNameFromId(repoId));
        rec = dataStore.getMetadataRecord(SharedStoreRecordType.REFERENCES.getNameFromId(repoId));
        refsReturned = FileIOUtils.readStringsAsSet(rec.getStream(), false);
        Assert.assertEquals(refs, refsReturned);
        assertEquals(
            SharedStoreRecordType.REFERENCES.getIdFromName(rec.getIdentifier().toString()),
            repoId);
        dataStore.deleteAllMetadataRecords(SharedStoreRecordType.REFERENCES.getType());
    }

    @Test
    public void testGetAllChunkIds() throws Exception {
        File rootFolder = folder.newFolder();
        dataStore = getBlobStore(rootFolder);
        int number = 10;
        Set<String> added = newHashSet();
        for (int i = 0; i < number; i++) {
            String rec = dataStore.writeBlob(randomStream(i, 16516));
            added.add(rec);
        }

        Set<String> retrieved = newHashSet(dataStore.getAllChunkIds(0));
        assertEquals(added, retrieved);
    }

    @Test
    public void testGetAllRecords() throws Exception {
        File rootFolder = folder.newFolder();
        dataStore = getBlobStore(rootFolder);
        int number = 10;
        Set<String> added = newHashSet();
        for (int i = 0; i < number; i++) {
            String rec = dataStore.addRecord(randomStream(i, 16516))
                .getIdentifier().toString();
            added.add(rec);
        }

        Set<String> retrieved = newHashSet(Iterables.transform(newHashSet(dataStore.getAllRecords()),
            new Function<DataRecord, String>() {
                @Nullable @Override public String apply(@Nullable DataRecord input) {
                    return input.getIdentifier().toString();
                }
            }));
        assertEquals(added, retrieved);
    }

    @Test
    public void testStreamFromGetAllRecords() throws Exception {
        File rootFolder = folder.newFolder();
        dataStore = getBlobStore(rootFolder);
        int number = 10;
        Set<DataRecord> added = newHashSet();
        for (int i = 0; i < number; i++) {
            added.add(dataStore.addRecord(randomStream(i, 16516)));
        }

        Set<DataRecord> retrieved = newHashSet((dataStore.getAllRecords()));
        assertRecords(added, retrieved);
    }

    @Test
    public void testGetRecordForId() throws Exception {
        File rootFolder = folder.newFolder();
        dataStore = getBlobStore(rootFolder);
        int number = 10;
        Set<DataRecord> added = newHashSet();
        for (int i = 0; i < number; i++) {
            added.add(dataStore.addRecord(randomStream(i, 16516)));
        }

        Set<DataRecord> retrieved = newHashSet();
        for (DataRecord rec : added) {
            retrieved.add(dataStore.getRecordForId(rec.getIdentifier()));
        }
        assertRecords(added, retrieved);
    }

    private static void assertRecords(Set<DataRecord> expected, Set<DataRecord> retrieved)
        throws DataStoreException, IOException {
        //assert streams
        Map<DataIdentifier, DataRecord> retMap = Maps.newHashMap();
        for (DataRecord ret : retrieved) {
            retMap.put(ret.getIdentifier(), ret);
        }

        for (DataRecord rec : expected) {
            assertEquals("Record id different for " + rec.getIdentifier(),
                rec.getIdentifier(), retMap.get(rec.getIdentifier()).getIdentifier());
            assertEquals("Record length different for " + rec.getIdentifier(),
                rec.getLength(), retMap.get(rec.getIdentifier()).getLength());
            assertEquals("Record lastModified different for " + rec.getIdentifier(),
                rec.getLastModified(), retMap.get(rec.getIdentifier()).getLastModified());
            assertTrue("Record steam different for " + rec.getIdentifier(),
                IOUtils.contentEquals(rec.getStream(), retMap.get(rec.getIdentifier()).getStream()));
        }
    }

    static InputStream randomStream(int seed, int size) {
        Random r = new Random(seed);
        byte[] data = new byte[size];
        r.nextBytes(data);
        return new ByteArrayInputStream(data);
    }
}

redpajama_set_name: RedPajamaGithub


text:
using namespace std;

namespace Lisp {

// there is one global ennvironment at the root of everything
LispEnvRef LispEnv::globalEnv = LispEnvRef(new LispEnv);

// constructor - new environment is constructed referring to
// it's parent, normally, but this is for the global environment
LispEnv::LispEnv() : parent_(LispEnvRef()) {
	fEnv_["QUOTE"]   = make_literal(PrimType(LispQuote::quote_fn));
	fEnv_["SET!"]    = make_literal(PrimType(LispEnv::set_fn));
	fEnv_["DEFINE"]  = make_literal(PrimType(LispEnv::define_fn));
	fEnv_["FN"]      = make_literal(PrimType(LispEnv::defun_fn));
	fEnv_["CAR"]     = make_literal(PrimType(LispEnv::car_fn));
	fEnv_["CDR"]     = make_literal(PrimType(LispEnv::cdr_fn));
	fEnv_["PRINT"]   = make_literal(PrimType(LispEnv::print_fn));
	fEnv_["LAMBDA"]  = make_literal(PrimType(LispEnv::lambda_fn));
	fEnv_["IF"]      = make_literal(PrimType(LispEnv::if_fn));
	fEnv_["PROGN"]   = make_literal(PrimType(LispEnv::prog_fn));
}

// constructor - new environment created with parent
LispEnv::LispEnv(LispEnvRef parentEnv) : parent_(parentEnv) {
}

// resolve a reference to a symbol in an environment
// corresponds to lookup-variable-value in sicp
LispObjRef LispEnv::ref(std::string var)  {
	EnvironmentT::iterator it(env_.find(var));
	if(it != env_.end()) {
		return it->second;
	};
	if(parent_ != NULL) {
		return parent_->ref(var);
	}
	return nil;
}

// bind a symnbol to a variable in this environment
// corresponts to set-variable-value! in sicp
LispObjRef LispEnv::set(std::string var, LispObjRef ref) {
	EnvironmentT::iterator it(env_.find(var));
	if(it != env_.end()) {
		it->second = ref;
		return ref;
	} else {
		env_[var] = ref;
	}
	return nil;
}

// bind a symnbol to a variable in this environment
LispObjRef LispEnv::define(std::string var, LispObjRef ref) {
	EnvironmentT::iterator it(env_.find(var));
	if(it != env_.end()) {
		it->second = ref;
	} else {
		env_[var] = ref;
	}
	return ref;
}

// resolve a reference to a function in an environment
LispObjRef LispEnv::fref(std::string var)  {
	EnvironmentT::iterator it(fEnv_.find(var));
	if(it != fEnv_.end()) {
		return it->second;
	};
	if(parent_ != NULL) {
		return parent_->fref(var);
	}
	return nil;
}

// set the value associated with a symbol in an environment
LispObjRef LispEnv::fset(std::string var, LispObjRef ref) {
	fEnv_[var] = ref;
	return ref;
}

// Function used for the (set ) special form - bind car to cons
LispObjRef LispEnv::set_fn(LispObjRef cons, LispEnvRef env) {
	// car of cons should be a symbol
	if(is_symbol(car(cons)))
		return env->set(get_ctype<SymbolType>(car(cons)).name, eval(cadr(cons), env));
	return nil;
}

LispObjRef LispEnv::define_fn(LispObjRef cons, LispEnvRef env) {
	if(is_symbol(car(cons)))
		return env->define(get_ctype<SymbolType>(car(cons)).name, eval(cadr(cons), env));
	return nil;
}

LispObjRef LispEnv::defun_fn(LispObjRef cons, LispEnvRef env) {
	if(is_symbol(car(cons)))
		env->fset(get_ctype<SymbolType>(car(cons)).name, eval(cadr(cons), env));
	return car(cons);
}

LispObjRef LispEnv::car_fn(LispObjRef cons, LispEnvRef env) {
	return car(eval(cadr(cons), env));
}

LispObjRef LispEnv::cdr_fn(LispObjRef cons, LispEnvRef env) {
	return cdr(eval(cadr(cons), env));
}

LispObjRef LispEnv::print_fn(LispObjRef cons, LispEnvRef env) {
	Printer::printer->print(eval(cadr(cons), env));
	return nil;
}

LispObjRef LispEnv::lambda_fn(LispObjRef cons, LispEnvRef env) {
	(void) env;
	// really just returns an unevaluated cons
	LispObjRef args = car(cons);
	LispObjRef body = car(cdr(cons));
	return make_lambda(args, body);
}

LispObjRef LispEnv::apply_fn(LispObjRef cons, LispEnvRef env) {
	LispObjRef result = nil;
	// should be a cons cell [apply|-]-[fn|-]-[arg0|-]-[arg1|-]-...
	LispObjRef obj = eval(cadr(cons), env);
	// [fn|-]-[arg0|-]-[arg1|-]-...||
    // [.|-]-[arg0|-]-[arg1]-[
	// [lambda|-]-
	if (is_cons(obj))
	{
		// must be function invocation -- function symbol
		LispObjRef fnsym(car(obj));
		if (is_symbol(fnsym) || is_primitive(fnsym)) {
			// it's a function
			LispObjRef fn = is_symbol(fnsym) ? env->fref(get_ctype<SymbolType>(fnsym).name) : fnsym;
			if (is_primitive(fn)) {
				CPrim cfn = (CPrim)(boost::get<PrimType>(*fn));
				// call it on the cdr
				result = cfn(cdr(obj), env);
			}
		}
		if (is_cons(fnsym)) {
			LispObjRef lambda(eval(car(fnsym), env));
			if (is_cons(lambda)) {
				// this should be a lambda form - args are car, cdr is body
				LispObjRef params = car(lambda);
				LispObjRef args   = cddr(obj);
				LispEnvRef lambda_env(new LispEnv(env));
				LispObjRef param;
				LispObjRef arg;
				do {
					param = car(params);
					arg = car(args);
					lambda_env->set(get_ctype<SymbolType>(param).name, eval(arg,env));
					param = cadr(params);
					arg = is_nil(arg) ? nil : cadr(args);
				} while (!is_nil(param));
				result = eval(cdr(lambda), lambda_env);
			}
		}
	}
	return result;
}

LispObjRef  LispEnv::if_fn(LispObjRef cons, LispEnvRef env) {
	LispObjRef condition = car(cons);
	LispObjRef result = eval(condition, env);
	LispObjRef trueclause = cadr(cons);
	LispObjRef falseclause = car(cdr(cdr(cons)));
	if(!is_nil(result)) {
		return eval(trueclause, env);
	} else {
		return eval(falseclause, env);
	}
}

LispObjRef LispEnv::prog_fn(LispObjRef cons, LispEnvRef env) {
	LispObjRef result = nil;
	LispObjRef fnx = cons;
	while(!is_nil(fnx)) {
		LispObjRef arg = car(fnx);
		result = eval(arg, env);
		fnx = cdr(fnx);
	}
	return result;
}
} // namespace Lisp


text:
package main

import (
	"github.com/1lann/beacon/protocol"
	"net"
	"time"
)

func (s *Server) IsMinecraftServerResponding() bool {
	conn, err := net.DialTimeout("tcp", s.IPAddress+":25565", time.Second*5)
	if err != nil {
		return false
	}

	defer conn.Close()

	conn.SetDeadline(time.Now().Add(time.Second * 5))

	stream := protocol.NewStream(conn)
	handshake := protocol.NewPacketWithID(0x00)
	handshake.WriteVarInt(5)
	handshake.WriteString(s.IPAddress)
	handshake.WriteUInt16(25565)
	handshake.WriteVarInt(1)
	if err := stream.WritePacket(handshake); err != nil {
		return false
	}

	request := protocol.NewPacketWithID(0x00)
	if err := stream.WritePacket(request); err != nil {
		return false
	}

	conn.SetDeadline(time.Now().Add(time.Second * 5))

	_, length, err := stream.GetPacketStream()
	if err != nil {
		return false
	}

	if length > 5 {
		return true
	}

	return false
}

func startResponseMonitor() {
	for {
		for _, server := range allServers {
			if !server.Available {
				continue
			}

			server.StateLock.Lock()

			if server.IsMinecraftServerResponding() {
				if server.State != stateShutdown &&
					server.State != stateSnapshot &&
					server.State != stateDestroy {
					server.SetState(stateStarted)
				}
			} else {
				if server.State == stateStarted {
					server.SetState(stateUnavailable)
				}
			}

			server.StateLock.Unlock()
		}

		time.Sleep(time.Second * 5)
	}
}


text:
finger.js
=========

Lightweight library to abstract mouse/touch/pointer events into "taps" for gaming.

Allows event-based and direct access to taps, clicks, dragging, gestures, path.

Library is not made for DOM applications, as taps will not contain any information about elements or collisions. Events are screen based (window), and have only coordinates of their presence, as well as state.
This is perfect for gaming applications with canvas, or applications based on gestures rather than element events.


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

package dicom

import (
	"fmt"
	"io"
	"math"
)

// DataElementWriter writes DataElements one at a time
type DataElementWriter interface {
	WriteElement(element *DataElement) error
}

var errExpectedMetaHeader = fmt.Errorf("expected header to only contain file meta elements, " +
	"use DataSet.MetaElements to filter DataSet")

// NewDataElementWriter writes the DICOM preamble, signature, and meta header to w and returns a
// DataElementWriter that writes DataElements in the transfer syntax specified by the header.
// The options are applied in the order given to all DataElements including File Meta Elements
// before being written to w.
func NewDataElementWriter(w io.Writer, header *DataSet, opts ...ConstructOption) (DataElementWriter, error) {
	if !header.isMetaHeader() {
		return nil, errExpectedMetaHeader
	}

	syntax, err := header.transferSyntax()
	if err != nil {
		return nil, fmt.Errorf("getting transfer syntax from header: %v", err)
	}
	if syntax == deflatedExplicitVRLittleEndian {
		return nil, fmt.Errorf("writing in the deflated syntax is not supported yet")
	}

	dw := &dcmWriter{w}
	if err := writeDicomSignature(dw); err != nil {
		return nil, err
	}

	// Process meta header elements before re-calculating the FileMetaInformationGroupLength in case
	// an option modifies the length of a DataElement.
	for tag, element := range header.Elements {
		element, err := processElementForConstruct(element, explicitVRLittleEndian, opts...)
		if err != nil {
			return nil, fmt.Errorf("processing element: %v", err)
		}
		header.Elements[tag] = element
	}

	// The FileMetaInformationGroupLength element is a critical component of the Meta Header. It
	// stores how long the meta header is. Thus, we need to re-calculate it properly.
	metaGroupLengthElement, err := createMetaGroupLengthElement(header)
	if err != nil {
		return nil, fmt.Errorf("creating meta group length element: %v", err)
	}
	header.Elements[FileMetaInformationGroupLengthTag] = metaGroupLengthElement

	// Meta elements are always written in the Explicit VR Little Endian syntax in ascending order.
	for _, element := range header.SortedElements() {
		if err := writeDataElement(dw, explicitVRLittleEndian, element); err != nil {
			return nil, fmt.Errorf("writing data element: %v", err)
		}
	}

	return &dataElementWriter{dw, syntax, opts}, nil
}

type dataElementWriter struct {
	dw     *dcmWriter
	syntax transferSyntax
	opts   []ConstructOption
}

func (dew *dataElementWriter) WriteElement(element *DataElement) error {
	element, err := processElementForConstruct(element, dew.syntax, dew.opts...)
	if err != nil {
		return err
	}
	return writeDataElement(dew.dw, dew.syntax, element)
}

func writeDicomSignature(dw *dcmWriter) error {
	if err := dw.Bytes(make([]byte, 128)); err != nil {
		return fmt.Errorf("writing DICOM preamble: %v", err)
	}

	if err := dw.String("DICM"); err != nil {
		return fmt.Errorf("writing DICOM signature: %v", err)
	}

	return nil
}

func createMetaGroupLengthElement(header *DataSet) (*DataElement, error) {
	// Please refer to the DICOM Standard Part 10 for information on the File Meta Information Group
	// Length. http://dicom.nema.org/medical/dicom/current/output/html/part10.html#sect_7.1

	size := uint32(0)
	for _, element := range header.Elements {
		if element.Tag == FileMetaInformationGroupLengthTag {
			// The FileMetaGroupLength byte count excludes itself from the calculation.
			continue
		}
		size += explicitVRLittleEndian.elementSize(element.VR, element.ValueLength)
	}

	return &DataElement{
		Tag:         FileMetaInformationGroupLengthTag,
		VR:          FileMetaInformationGroupLengthTag.DictionaryVR(),
		ValueField:  []uint32{size},
		ValueLength: 4, // 4bytes = sizeof uint32
	}, nil
}

func processElementForConstruct(element *DataElement, syntax transferSyntax, opts ...ConstructOption) (*DataElement, error) {
	element, err := applyConstructOptions(element, syntax, opts...)
	if err != nil {
		return nil, fmt.Errorf("applying construct options: %v", err)
	}

	if seq, ok := element.ValueField.(*Sequence); ok {
		processedSeq, err := processSequenceForConstruct(seq, syntax, opts...)
		if err != nil {
			return nil, fmt.Errorf("processing sequence: %v", err)
		}
		element.ValueField = processedSeq
	}

	return element, nil
}

func applyConstructOptions(element *DataElement, syntax transferSyntax, opts ...ConstructOption) (*DataElement, error) {
	var err error
	for i, opt := range opts {
		element, err = opt.transform(element)
		if err != nil {
			return nil, fmt.Errorf("applying option %v: %v", i, err)
		}
	}

	// As documented in NewConstructOption, after a transforms are applied, the length is
	// re-calculated and VRs added from the Data Dictionary if nil
	vr := element.VR
	if vr == nil {
		vr = element.Tag.DictionaryVR()
	}

	length, err := calculateElementLength(element, syntax)
	if err != nil {
		return nil, fmt.Errorf("calculating element length: %v", err)
	}

	return &DataElement{element.Tag, vr, element.ValueField, length}, nil
}

func calculateElementLength(element *DataElement, syntax transferSyntax) (uint32, error) {
	if element.ValueLength == UndefinedLength {
		return UndefinedLength, nil
	}

	numBytes := int64(0)

	switch v := element.ValueField.(type) {
	case []string:
		for _, s := range v {
			numBytes += int64(len(s))
		}
		if len(v) > 0 { // requires "/" delimiter
			numBytes += int64(len(v)) - 1
		}
	case []int16:
		numBytes = int64(len(v)) * 2
	case []uint16:
		numBytes = int64(len(v)) * 2
	case []int32:
		numBytes = int64(len(v)) * 4
	case []uint32:
		numBytes = int64(len(v)) * 4
	case []float32:
		numBytes = int64(len(v)) * 4
	case []float64:
		numBytes = int64(len(v)) * 8
	case *Sequence:
		seqLen, err := calculateSequenceLength(v, syntax)
		if err != nil {
			return 0, fmt.Errorf("calculating sequence length: %v", err)
		}
		numBytes = int64(seqLen)
	case SequenceIterator:
		numBytes = UndefinedLength // TODO support explicit length sequence construction
	case BulkDataBuffer:
		numBytes = v.Length()
		if numBytes < 0 {
			return 0, fmt.Errorf("explicit length must be provided to write BulkDataBuffer")
		}
	case BulkDataIterator:
		numBytes = v.Length()
		if numBytes < 0 {
			return 0, fmt.Errorf("explicit length must be provided to write BulkDataIterator")
		}
	default:
		return 0, fmt.Errorf("unexpected ValueField type %T", element.ValueField)
	}

	if numBytes >= math.MaxUint32 {
		return UndefinedLength, nil
	}

	if numBytes%2 != 0 {
		numBytes++
	}

	return uint32(numBytes), nil
}

func calculateSequenceLength(seq *Sequence, syntax transferSyntax) (uint32, error) {
	size := int64(0)
	for _, item := range seq.Items {
		itemLen, err := calculateDataSetLength(item, syntax)
		if err != nil {
			return 0, fmt.Errorf("calculating sequence item length: %v", err)
		}
		item.Length = itemLen
		size += tagSize + 4 /*32 bit length*/ + int64(itemLen)
	}

	if size > math.MaxUint32 {
		return UndefinedLength, nil
	}

	return uint32(size), nil
}

func calculateDataSetLength(item *DataSet, syntax transferSyntax) (uint32, error) {
	if item.Length >= UndefinedLength {
		return UndefinedLength, nil
	}

	size := int64(0)
	for _, elem := range item.Elements {
		elemLength, err := calculateElementLength(elem, syntax)
		if err != nil {
			return 0, fmt.Errorf("calculating data set element length: %v", err)
		}
		size += int64(syntax.elementSize(elem.VR, elemLength))
	}

	if size > math.MaxUint32 {
		return UndefinedLength, nil
	}

	return uint32(size), nil
}

func processSequenceForConstruct(sequence *Sequence, syntax transferSyntax, opts ...ConstructOption) (*Sequence, error) {
	ret := &Sequence{Items: []*DataSet{}}
	for _, item := range sequence.Items {
		processedItem, err := processItemForConstruct(item, syntax, opts...)
		if err != nil {
			return nil, fmt.Errorf("processing sequence item: %v", err)
		}
		ret.append(processedItem)
	}
	return ret, nil
}

func processItemForConstruct(dataSet *DataSet, syntax transferSyntax, opts ...ConstructOption) (*DataSet, error) {
	ret := &DataSet{Elements: map[DataElementTag]*DataElement{}, Length: dataSet.Length}
	for _, element := range dataSet.SortedElements() {
		processedElement, err := processElementForConstruct(element, syntax, opts...)
		if err != nil {
			return nil, fmt.Errorf("processing element %s", element.Tag)
		}
		ret.Elements[processedElement.Tag] = processedElement
	}
	return ret, nil
}


text:
@interface UITableViewCell (CellController)

@property (nonatomic, assign) id<ABTableViewCellController> cellController;

- (void)updateCellWithObject:(id)object;

@end


text:
from django.forms.utils import flatatt
from django.forms.widgets import DateTimeInput
from django.utils.safestring import mark_safe
from django.utils import translation
from django.utils.html import conditional_escape
from django.utils.encoding import force_text

import json

class DatePicker(DateTimeInput):
    class Media:
        #if you need a different local add it to the below string - example 'js/locales/bootstrap-datepicker.en-GB.min.js'
        js = ('js/bootstrap-datepicker.min.js',)
        css = {'all': ('css/bootstrap-datepicker3.standalone.min.css',), }
    # http://bootstrap-datepicker.readthedocs.org/en/stable/options.html#format
    # http://docs.python.org/2/library/datetime.html#strftime-strptime-behavior

    format_map = (
        ('dd', r'%d'),
        ('DD', r'%A'),
        ('D', r'%a'),
        ('MM', r'%B'),
        ('M', r'%b'),
        ('mm', r'%m'),
        ('yyyy', r'%Y'),
        ('yy', r'%y'),
    )

    @classmethod
    def conv_datetime_format_py2js(cls, format):
        for js, py in cls.format_map:
            format = format.replace(py, js)
        return format

    @classmethod
    def conv_datetime_format_js2py(cls, format):
        for js, py in cls.format_map:
            format = format.replace(js, py)
        return format

    html_template = '''

            <input%(input_attrs)s/>

'''

    js_template = '''
        '''

    def __init__(self, attrs=None, format=None, options=None, div_attrs=None, icon_attrs=None):
        if not icon_attrs:
            icon_attrs = {'class': 'fa fa-calendar fa-2'}
        if not div_attrs:
            div_attrs = {'class': 'input-group date'}
        if format is None and options and options.get('format'):
            format = self.conv_datetime_format_js2py(options.get('format'))
        super(DatePicker, self).__init__(attrs, format)
        if 'class' not in self.attrs:
            self.attrs['class'] = 'form-control'
        self.div_attrs = div_attrs and div_attrs.copy() or {}
        self.icon_attrs = icon_attrs and icon_attrs.copy() or {}
        self.picker_id = self.div_attrs.get('id') or None
        if options == False:  # datepicker will not be initalized when options is False
            self.options = False
        else:
            self.options = options and options.copy() or {}
            if format and not self.options.get('format') and not self.attrs.get('date-format'):
                self.options['format'] = self.conv_datetime_format_py2js(format)

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

        extra_attrs = dict()
        extra_attrs['type'] = self.input_type
        extra_attrs['name'] = name
        input_attrs = self.build_attrs(attrs, extra_attrs)

        if value != '':
            # Only add the 'value' attribute if a value is non-empty.
            input_attrs['value'] = force_text(self.format_value(value))
        input_attrs = {key: conditional_escape(val) for key, val in input_attrs.items()}

        if not self.picker_id:
            self.picker_id = (input_attrs.get('id', '') + '_pickers').replace(' ', '_')
        self.div_attrs['id'] = self.picker_id
        picker_id = conditional_escape(self.picker_id)
        div_attrs = {key: conditional_escape(val) for key, val in self.div_attrs.items()}
        icon_attrs = {key: conditional_escape(val) for key, val in self.icon_attrs.items()}
        html = self.html_template % dict(div_attrs=flatatt(div_attrs),
                                         input_attrs=flatatt(input_attrs),
                                         icon_attrs=flatatt(icon_attrs))
        if self.options:
            js = self.js_template % dict(picker_id=picker_id, options=json.dumps(self.options or {}))
        else:
            js = ''
        return mark_safe(force_text(html + js))


text:
package io.fabric8.kubernetes.api.extensions;

import io.fabric8.kubernetes.api.KubernetesHelper;
import io.fabric8.kubernetes.api.model.*;
import io.fabric8.utils.Objects;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * Helper class for working with the YAML config file thats located in
 * ~/.kube/config which is updated when you use commands
 * like oc login and oc project myproject
 */
public class Configs {
    public static final String KUBERNETES_CONFIG_FILE_PROPERTY = "kubernetes.config.file";
    public static final String KUBERNETES_CONFIG_FILE_ENV_VAR = "KUBECONFIG";
    private static final transient Logger LOG = LoggerFactory.getLogger(Configs.class);

    public static Config parseConfigs() {
        File file = getKubernetesConfigFile();
        if (file.exists() && file.isFile()) {
            try {
                return KubernetesHelper.loadYaml(file, Config.class);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * Returns the current context in the given config
     */
    public static Context getCurrentContext(Config config) {
        String contextName = config.getCurrentContext();
        if (contextName != null) {
            List<NamedContext> contexts = config.getContexts();
            if (contexts != null) {
                for (NamedContext context : contexts) {
                    if (Objects.equal(contextName, context.getName())) {
                        return context.getContext();
                    }
                }
            }
        }
        return null;
    }

    /**
     * Returns the current user token for the config and current context
     */
    public static String getUserToken(Config config, Context context) {
        AuthInfo authInfo = getUserAuthInfo(config, context);
        if (authInfo != null) {
            return authInfo.getToken();
        }
        return null;
    }

    /**
     * Returns the current {@link AuthInfo} for the current context and user
     */
    public static AuthInfo getUserAuthInfo(Config config, Context context) {
        AuthInfo authInfo = null;
        if (config != null && context != null) {
            String user = context.getUser();
            if (user != null) {
                List<NamedAuthInfo> users = config.getUsers();
                if (users != null) {
                    for (NamedAuthInfo namedAuthInfo : users) {
                        if (Objects.equal(user, namedAuthInfo.getName())) {
                            authInfo = namedAuthInfo.getUser();
                        }
                    }
                }
            }
        }
        return authInfo;
    }

    /**
     * Returns the current {@link Cluster} for the current context
     */
    public static Cluster getCluster(Config config, Context context) {
        Cluster cluster = null;
        if (config != null && context != null) {
            String clusterName = context.getCluster();
            if (clusterName != null) {
                List<NamedCluster> clusters = config.getClusters();
                if (clusters != null) {
                    for (NamedCluster namedCluster : clusters) {
                        if (Objects.equal(clusterName, namedCluster.getName())) {
                            cluster = namedCluster.getCluster();
                        }
                    }
                }
            }
        }
        return cluster;
    }

    public static File getKubernetesConfigFile() {
        String file = System.getProperty(KUBERNETES_CONFIG_FILE_PROPERTY);
        if (file != null) {
            return new File(file);
        }
        file = System.getenv(KUBERNETES_CONFIG_FILE_ENV_VAR);
        if (file != null) {
            return new File(file);
        }
        String homeDir = System.getProperty("user.home", ".");
        return new File(homeDir, ".kube/config");
    }
}


text:
<?php
        include_once('js/BitlyPHP/bitly.php');
        $access_token = "";
        if($_GET['deckurl']) {
            $params = array();
            $params['access_token'] = $access_token;
            $params['longUrl'] = base64_decode($_GET['deckurl']);
            $results = bitly_get('shorten', $params);
            header('Content-type: application/json');
            header('Access-Control-Allow-Origin: *');
            echo json_encode($results);
        }
?>


text:
module Azure::Subscriptions::Mgmt::V2017_11_01_preview
  module Models
    #
    # Subscription Definition List operation response.
    #
    class SubscriptionDefinitionList

      include MsRestAzure

      include MsRest::JSONable
      # @return [Array<SubscriptionDefinition>] An array of
      # subscriptionDefinitions
      attr_accessor :value

      # @return [String] URL to get the next set of operation list results if
      # there are any.
      attr_accessor :next_link

      # return [Proc] with next page method call.
      attr_accessor :next_method

      #
      # Gets the rest of the items for the request, enabling auto-pagination.
      #
      # @return [Array<SubscriptionDefinition>] operation results.
      #
      def get_all_items
        items = @value
        page = self
        while page.next_link != nil && !page.next_link.strip.empty? do
          page = page.get_next_page
          items.concat(page.value)
        end
        items
      end

      #
      # Gets the next page of results.
      #
      # @return [SubscriptionDefinitionList] with next page content.
      #
      def get_next_page
        response = @next_method.call(@next_link).value! unless @next_method.nil?
        unless response.nil?
          @next_link = response.body.next_link
          @value = response.body.value
          self
        end
      end

      #
      # Mapper for SubscriptionDefinitionList class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'SubscriptionDefinitionList',
          type: {
            name: 'Composite',
            class_name: 'SubscriptionDefinitionList',
            model_properties: {
              value: {
                client_side_validation: true,
                required: false,
                serialized_name: 'value',
                type: {
                  name: 'Sequence',
                  element: {
                      client_side_validation: true,
                      required: false,
                      serialized_name: 'SubscriptionDefinitionElementType',
                      type: {
                        name: 'Composite',
                        class_name: 'SubscriptionDefinition'
                      }
                  }
                }
              },
              next_link: {
                client_side_validation: true,
                required: false,
                serialized_name: 'nextLink',
                type: {
                  name: 'String'
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
MongoDB\Driver\TopologyDescription::getServers()
--SKIPIF--
<?php require __DIR__ . "/../utils/basic-skipif.inc"; ?>
<?php skip_if_not_live(); ?>
--FILE--
<?php
require_once __DIR__ . "/../utils/basic.inc";

class TopologyDescriptionProvider implements MongoDB\Driver\Monitoring\SDAMSubscriber
{
    private $topologyDescription;

    public function serverChanged(MongoDB\Driver\Monitoring\ServerChangedEvent $event) {}

    public function serverClosed(MongoDB\Driver\Monitoring\ServerClosedEvent $event) {}

    public function serverHeartbeatFailed(MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent $event) {}

    public function serverHeartbeatStarted(MongoDB\Driver\Monitoring\ServerHeartbeatStartedEvent $event) {}

    public function serverHeartbeatSucceeded(MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent $event) {}

    public function serverOpening(MongoDB\Driver\Monitoring\ServerOpeningEvent $event) {}

    public function topologyChanged(MongoDB\Driver\Monitoring\TopologyChangedEvent $event)
    {
        $this->topologyDescription = $event->getNewDescription();
    }

    public function topologyClosed(MongoDB\Driver\Monitoring\TopologyClosedEvent $event) {}

    public function topologyOpening(MongoDB\Driver\Monitoring\TopologyOpeningEvent $event) {}

    public function getTopologyDescription()
    {
        $manager = create_test_manager();
        $manager->addSubscriber($this);
        $manager->executeCommand(DATABASE_NAME, new MongoDB\Driver\Command(['ping' => 1]));
        $manager->removeSubscriber($this);

        return $this->topologyDescription;
    }
}

function isArrayOfServerDescriptions(array $sds) {
    if (count($sds) < 1) {
        return false;
    }

    foreach ($sds as $sd) {
        if (! $sd instanceof MongoDB\Driver\ServerDescription) {
            return false;
        }
    }

    return true;
}

$subscriber = new TopologyDescriptionProvider;
$topologyDescription = $subscriber->getTopologyDescription();
$serverDescriptions = $topologyDescription->getServers();

var_dump(isArrayOfServerDescriptions($serverDescriptions));

?>
===DONE===
<?php exit(0); ?>
--EXPECT--
bool(true)
===DONE===


text:
package vm

import (
	"errors"
	"fmt"
	"regexp"
	"strconv"
)

var (
	portRangeRegexp = regexp.MustCompile(`\A([1-9][0-9]*)(\s*[\-:]\s*([1-9][0-9]*))?\z`)
)

type PortMapping struct {
	host      PortRange
	container PortRange
	protocol  string
}

func NewPortMapping(host, container PortRange, protocol string) (PortMapping, error) {
	if host.Len() != container.Len() {
		return PortMapping{}, errors.New("Host and container port ranges must have same length")
	}
	if len(protocol) == 0 {
		return PortMapping{}, errors.New("Protocol must be specified")
	}
	if host.Len() > 1 {
		if !host.Same(container) {
			return PortMapping{}, errors.New("Host and container port ranges must be same")
		}
		if protocol != "tcp" && protocol != "udp" {
			return PortMapping{}, errors.New("Port ranges can only be used with tcp or udp protocol")
		}
	}
	return PortMapping{host: host, container: container, protocol: protocol}, nil
}

func (m PortMapping) Host() PortRange      { return m.host }
func (m PortMapping) Container() PortRange { return m.container }
func (m PortMapping) Protocol() string     { return m.protocol }

type PortRange struct {
	start, end int // both ends are inclusive
}

func NewPortRange(start, end int) (PortRange, error) {
	if start <= 0 || start > 65535 {
		return PortRange{}, errors.New("Port range start must be > 0 and <= 65535")
	}
	if end <= 0 || end > 65535 {
		return PortRange{}, errors.New("Port range end must be > 0 and <= 65535")
	}
	if start > end {
		return PortRange{}, errors.New("Port range start must be <= end")
	}
	return PortRange{start: start, end: end}, nil
}

func NewPortRangeFromString(s string) (PortRange, error) {
	matches := portRangeRegexp.FindStringSubmatch(s)
	if len(matches) == 0 {
		return PortRange{}, fmt.Errorf("Port range must match '%s'", portRangeRegexp)
	}

	if len(matches) != 4 {
		panic("Internal inconsistency: port range regexp mismatch")
	}

	start, err := strconv.Atoi(matches[1])
	if err != nil {
		panic(fmt.Sprintf("Expected '%s' to be an int", matches[1]))
	}

	// matches[2] is delim

	switch {
	case matches[3] == "":
		return NewPortRange(start, start)

	default:
		end, err := strconv.Atoi(matches[3])
		if err != nil {
			panic(fmt.Sprintf("Expected '%s' to be an int", matches[3]))
		}
		return NewPortRange(start, end)
	}
}

func (r PortRange) Start() int { return r.start }
func (r PortRange) End() int   { return r.end }
func (r PortRange) Len() int   { return r.end - r.start + 1 }

func (r PortRange) Same(other PortRange) bool {
	return r.start == other.start && r.end == other.end
}


text:
package main

import (
	"fmt"
	"os"
	"os/exec"
	"strings"
)

// A Dependency is a specific revision of a package.
type Dependency struct {
	ImportPath string
	Comment    string `json:",omitempty"` // Description of commit, if present.
	Rev        string // VCS-specific commit ID.

	// used by command save & update
	ws   string // workspace
	root string // import path to repo root
	dir  string // full path to package

	// used by command update
	matched bool // selected for update by command line
	pkg     *Package

	// used by command go
	vcs *VCS
}

func eqDeps(a, b []Dependency) bool {
	ok := true
	for _, da := range a {
		for _, db := range b {
			if da.ImportPath == db.ImportPath && da.Rev != db.Rev {
				ok = false
			}
		}
	}
	return ok
}

// containsPathPrefix returns whether any string in a
// is s or a directory containing s.
// For example, pattern ["a"] matches "a" and "a/b"
// (but not "ab").
func containsPathPrefix(pats []string, s string) bool {
	for _, pat := range pats {
		if pat == s || strings.HasPrefix(s, pat+"/") {
			return true
		}
	}
	return false
}

func uniq(a []string) []string {
	i := 0
	s := ""
	for _, t := range a {
		if t != s {
			a[i] = t
			i++
			s = t
		}
	}
	return a[:i]
}

// goVersion returns the version string of the Go compiler
// currently installed, e.g. "go1.1rc3".
func goVersion() (string, error) {
	// Godep might have been compiled with a different
	// version, so we can't just use runtime.Version here.
	cmd := exec.Command("go", "version")
	cmd.Stderr = os.Stderr
	out, err := cmd.Output()
	if err != nil {
		return "", err
	}
	p := strings.Split(string(out), " ")
	if len(p) < 3 {
		return "", fmt.Errorf("Error splitting output of `go version`: Expected 3 or more elements, but there are < 3: %q", string(out))
	}
	return p[2], nil
}


text:
/** @hidden */
export abstract class IgxInputGroupBase {
    public disabled: boolean;
    public isFocused: boolean;
    public isRequired: boolean;
    public hasPlaceholder: boolean;
}


text:
published: true
title: Plum Loaf Cake
layout: post
categories: [cake]
rating: 4
---
### Servings
10

### Ingredients
- 1 1/2 sticks (3/4 cup) unsalted butter, softened at room temperature
- 1 cup dark brown sugar
- 3/4 cup Splenda (my attempt to feel better about eating even more cake this week - feel free to sub sugar)
- 2 eggs
- 1 tsp vanilla extract
- 1 tsp almond extract
- zest of one small lime
- 1 tsp ground cardamom
- 1 pint very ripe cherry-sized plums, pitted and separated into small pieces (skins on)
- 3 cups all purpose flour
- 1 tsp baking powder
- 1/2 tsp baking soda
- 1/2 tsp salt
- 2/3 cup vanilla yogurt (full or lowfat)
- 2/3 cup Skor toffee bits
- coarse turbinado or other raw sugar

### Directions
1. Preheat oven to 350 F. Grease a large loaf pan (preferably nonstick).
2. Cream together butter, sugar and splenda. Add eggs one at a time, mixing thoroughly after each one. Add extracts, zest and cardamom and stir to blend. Add in plums. Don't be worried if they get mashed to a pulp when you blend them in. Sift together remaining dry ingredients. Add 1/3 dry ingredients, then 1/3 cup yogurt, then the second third of dry ingredient, the rest of the yogurt, and finally add in toffee and remaining dry ingredients. Mix until just combined (don't overmix!) The batter should be just a little on the dry side of a normal cake batter.
3. Pour batter into the loaf pan and smooth the top with a spatula. Sprinkle with sugar. Bake for about 1 1/2 hours, or until a toothpick or skewer inserted into the middle comes out clean. Cool in pan 10 minutes, then turn out onto a cooling rack.

### Source
http://vanillabasil.blogspot.com/2008/08/plumtastic.html


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

import java.io.Serializable;

import org.activiti.engine.ActivitiIllegalArgumentException;
import org.activiti.engine.ActivitiObjectNotFoundException;
import org.activiti.engine.impl.interceptor.Command;
import org.activiti.engine.impl.interceptor.CommandContext;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.runtime.Execution;

/**
 * @author Tom Baeyens
 */
public class GetExecutionVariableCmd implements Command<Object>, Serializable {

  private static final long serialVersionUID = 1L;
  protected String executionId;
  protected String variableName;
  protected boolean isLocal;

  public GetExecutionVariableCmd(String executionId, String variableName, boolean isLocal) {
    this.executionId = executionId;
    this.variableName = variableName;
    this.isLocal = isLocal;
  }

  public Object execute(CommandContext commandContext) {
    if(executionId == null) {
      throw new ActivitiIllegalArgumentException("executionId is null");
    }
    if(variableName == null) {
      throw new ActivitiIllegalArgumentException("variableName is null");
    }

    ExecutionEntity execution = commandContext
      .getExecutionEntityManager()
      .findExecutionById(executionId);

    if (execution==null) {
      throw new ActivitiObjectNotFoundException("execution "+executionId+" doesn't exist", Execution.class);
    }

    Object value;

    if (isLocal) {
      value = execution.getVariableLocal(variableName);
    } else {
      value = execution.getVariable(variableName);
    }

    return value;
  }
}


text:
import os

from setuptools import setup, find_packages

here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, 'README.md')) as f:
    README = f.read()

requires = [
    'bokeh',
    'gitpython',
    'ipython',
    'jsonschema',
    'pyzmq',
    ]

setup(name='bokeh-playground',
      version='0.0',
      description='Bokeh playground',
      long_description=README,
      license="MIT License",
      classifiers=[
          "Programming Language :: Python",
      ],
      author='Austin Bingham',
      author_email='austin.bingham@gmail.com',
      url='',
      keywords='web pyramid pylons',
      packages=find_packages(),
      include_package_data=True,
      zip_safe=False,
      install_requires=requires,
      )


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Archimedes.Geometry._3D
{
    /// <summary>
    /// Represents a straight line in 3D space
    /// </summary>
    public struct StraightLine3
    {
        private Vector3 _start;
        private Vector3 _direction;

        /// <summary>
        /// Represents a start point of this straight line
        /// </summary>
        public Vector3 Start
        {
            get { return _start; }
            set { _start = value; }
        }

        /// <summary>
        /// Represents the direction of this line
        /// </summary>
        public Vector3 Direction
        {
            get { return _direction; }
            set { _direction = value; }
        }

        public StraightLine3(Vector3 start, Vector3 direction) : this()
        {
            Start = start;
            Direction = direction;
        }

        public bool Intersects(StraightLine3 other, out Vector3 intersection)
        {
            bool intersetcts = false;
            intersection = Vector3.Zero;

            return intersetcts;
        }

    }
}


text:
#ifndef ALLOY_COMPILER_PASSES_CONTEXT_PROMOTION_PASS_H_
#define ALLOY_COMPILER_PASSES_CONTEXT_PROMOTION_PASS_H_

#include "alloy/compiler/compiler_pass.h"

#if XE_COMPILER_MSVC
#pragma warning(push)
#pragma warning(disable : 4244)
#pragma warning(disable : 4267)
#include <llvm/ADT/BitVector.h>
#pragma warning(pop)
#else
#include <cmath>
#include <llvm/ADT/BitVector.h>
#endif  // XE_COMPILER_MSVC

namespace alloy {
namespace compiler {
namespace passes {

class ContextPromotionPass : public CompilerPass {
 public:
  ContextPromotionPass();
  virtual ~ContextPromotionPass() override;

  int Initialize(Compiler* compiler) override;

  int Run(hir::HIRBuilder* builder) override;

 private:
  void PromoteBlock(hir::Block* block);
  void RemoveDeadStoresBlock(hir::Block* block);

 private:
  std::vector<hir::Value*> context_values_;
  llvm::BitVector context_validity_;
};

}  // namespace passes
}  // namespace compiler
}  // namespace alloy

#endif  // ALLOY_COMPILER_PASSES_CONTEXT_PROMOTION_PASS_H_


text:
class SKYBOX
{
	public:
		SKYBOX(IDirect3DDevice9 *Dev, char fileName[], float size);
		~SKYBOX();
		void Render(D3DXVECTOR3 cameraPos);
		void GenerateEnvironmentMap(D3DXVECTOR3 position, bool saveToFile, TERRAIN &terrain);

	private:
		IDirect3DDevice9 *m_pDevice;
		std::vector<IDirect3DTexture9*> m_textures;
		ID3DXMesh *m_pMesh;
		D3DMATERIAL9 m_white;
};

#endif


text:
module POM

  class Profile

    # This module encapulates a few algorithms that attempt to infer
    # project metdata from various "common" parts of a project
    # For example, the project's name may be able to be infered from
    # a ruby file in the lib/ directory.
    #
    class Inference

      #
      def self.inference_methods
        @inference_methods ||= []
      end

      #
      def self.method_added(name)
        if name.to_s =~ /^infer_/
          inference_methods << name
        end
      end

      #
      attr :project

      #
      attr :root

      # Table of inferable metadata.
      attr :table

      #
      def initialize(project)
        @project = project
        @root    = project.root
        @table   = {}

        infer!
      end

      #
      def infer!
        self.class.inference_methods.each do |meth|
          send(meth)
        end
      end

      #
      def apply(profile)
        table.each do |key, value|
          profile[key] = value unless profile.value?(key)
        end
      end

      # Extract version from VERSION file.
      #--
      # TODO: It might be better to support the VERSION file as a separate class,
      # in the same way as we support README and MANFIEST.
      #
      # TODO: Support for codename?
      #++
      def infer_version_from_version_file
        vfile = root.glob('VERSION{,.txt,.yml,.yaml}', File::FNM_CASEFOLD).first
        if vfile && vfile.exist?
          text = vfile.read.strip
          case text
          when /\A---/
            type = :yaml
          when /\A\d+[.]/
            type = :text
          when /[:]/
            type = :yaml
          else
            type = nil
          end

          case type
          when :yaml
            data = YAML.load(text)
            data = data.inject({}){|h,(k,v)| h[k.to_sym]=v; h}
            text = data.values_at(:major,:minor,:patch,:build).compact.join('.')
            set :version, text
          when :text
            set :version, text
          end
        end
      end

      #
      #--
      # TODO: maybe in meta/ too?
      #++
      def infer_manifest
        if file = root.glob('manifest{,.txt}', :casefold).first
          set :manifest, File.basename(file)
        end
      end

      #
      def infer_from_readme
        readme = project.readme
        set :name, readme.name
        set :title, readme.title
        set :description, readme.description
        set :copyrights, readme.copyright
        set :authors, readme.authors
        set :resources, readme.resources
      end

      # Failing to find a name for the project, the last hope
      # is to discern it from the lib files.
      def infer_name_from_lib
        if file = root.glob('lib/*.rb').first
          name = file.basename.to_s.chomp('.rb')
          set :name, name
        end
      end

      private

      #
      def set(name, value)
        if value && @table[name.to_sym].nil?
          @table[name.to_sym] = value
        end
      end

    end

  end

end


text:
@interface RZArrayBackedTree : RZTree

- (instancetype)initWithChildren:(NSArray *)array;

- (instancetype)initWithChildren:(NSArray *)array representingObject:(id)representingObject;

@property (strong, nonatomic) id representedObject;

@property (strong, nonatomic) NSMutableArray *childrenStorage;

@end

@interface RZStaticArrayTree : RZArrayBackedTree

@end


text:
Aim of this library is to download *proper* version of web driver automatically, to help with Selenium-based testing.

Sample usage below

```
[Test]
public async Task should_get_latest_chrome_driver_and_run_selenium_go_to_url()
{
	//given
	var driverProvider = ProviderConfiguration.For(Browser.Chrome)
		.WithDesiredDriver(DesiredDriver.Latest)
		.BuildDriverProvider();

	//when
	await driverProvider.DownloadDriverBinary(_driverDirectory);

	//then
	Assert.DoesNotThrow(() =>
	{
		using (var driver = new ChromeDriver(_driverDirectory))
		{
			driver.Navigate().GoToUrl("google.com");
		}
	});
}
```

TODOs:

1. ~~Download latest version of chromedriver.exe~~ - done
2. Detect version of Chrome that is on machine and download latest compatible version of chromedriver.exe
3. Setup some continious integration
4. Publish on nuget
5. Implementation for Firefox
6. Implementation for Edge


text:
package gov.hhs.onc.sdcct.ws;

import gov.hhs.onc.sdcct.net.SdcctUris;
import gov.hhs.onc.sdcct.xml.SdcctXmlPrefixes;
import gov.hhs.onc.sdcct.xml.qname.utils.SdcctQnameUtils;
import javax.xml.namespace.QName;

public final class WsXmlQnames {
    public final static QName STACK_TRACE = SdcctQnameUtils.build(SdcctXmlPrefixes.SDCCT_WS, SdcctUris.SDCCT_WS_URN_VALUE, WsXmlNames.STACK_TRACE);

    private WsXmlQnames() {
    }
}