text:
package revel

import (
	"encoding/json"
	"fmt"
	"html/template"
	"io"
	"io/ioutil"
	"math"
	"mime/multipart"
	"os"
	"reflect"
	"strconv"
	"strings"
	"time"
)

const MaxInt = math.MaxInt64

// A Binder translates between string parameters and Go data structures.
type Binder struct {
	// Bind takes the name and type of the desired parameter and constructs it
	// from one or more values from Params.
	//
	// Example
	//
	// Request:
	//   url?id=123&ol[0]=1&ol[1]=2&ul[]=str&ul[]=array&user.Name=rob
	//
	// Action:
	//   Example.Action(id int, ol []int, ul []string, user User)
	//
	// Calls:
	//   Bind(params, "id", int): 123
	//   Bind(params, "ol", []int): {1, 2}
	//   Bind(params, "ul", []string): {"str", "array"}
	//   Bind(params, "user", User): User{Name:"rob"}
	//
	// Note that only exported struct fields may be bound.
	Bind func(params *Params, name string, typ reflect.Type) reflect.Value

	// Unbind serializes a given value to one or more URL parameters of the given
	// name.
	Unbind func(output map[string]string, name string, val interface{})
}

var binderLog = RevelLog.New("section", "binder")

// ValueBinder is adapter for easily making one-key-value binders.
func ValueBinder(f func(value string, typ reflect.Type) reflect.Value) func(*Params, string, reflect.Type) reflect.Value {
	return func(params *Params, name string, typ reflect.Type) reflect.Value {
		vals, ok := params.Values[name]
		if !ok || len(vals) == 0 {
			return reflect.Zero(typ)
		}
		return f(vals[0], typ)
	}
}

// Revel's default date and time constants
const (
	DefaultDateFormat     = "2006-01-02"
	DefaultDateTimeFormat = "2006-01-02 15:04"
)

// Binders type and kind definition
var (
	// These are the lookups to find a Binder for any type of data.
	// The most specific binder found will be used (Type before Kind)
	TypeBinders = make(map[reflect.Type]Binder)
	KindBinders = make(map[reflect.Kind]Binder)

	// Applications can add custom time formats to this array, and they will be
	// automatically attempted when binding a time.Time.
	TimeFormats = []string{}

	DateFormat     string
	DateTimeFormat string
	TimeZone       = time.UTC

	IntBinder = Binder{
		Bind: ValueBinder(func(val string, typ reflect.Type) reflect.Value {
			if len(val) == 0 {
				return reflect.Zero(typ)
			}
			intValue, err := strconv.ParseInt(val, 10, 64)
			if err != nil {
				binderLog.Warn("IntBinder Conversion Error", "error", err)
				return reflect.Zero(typ)
			}
			pValue := reflect.New(typ)
			pValue.Elem().SetInt(intValue)
			return pValue.Elem()
		}),
		Unbind: func(output map[string]string, key string, val interface{}) {
			output[key] = fmt.Sprintf("%d", val)
		},
	}

	UintBinder = Binder{
		Bind: ValueBinder(func(val string, typ reflect.Type) reflect.Value {
			if len(val) == 0 {
				return reflect.Zero(typ)
			}
			uintValue, err := strconv.ParseUint(val, 10, 64)
			if err != nil {
				binderLog.Warn("UintBinder Conversion Error", "error", err)
				return reflect.Zero(typ)
			}
			pValue := reflect.New(typ)
			pValue.Elem().SetUint(uintValue)
			return pValue.Elem()
		}),
		Unbind: func(output map[string]string, key string, val interface{}) {
			output[key] = fmt.Sprintf("%d", val)
		},
	}

	FloatBinder = Binder{
		Bind: ValueBinder(func(val string, typ reflect.Type) reflect.Value {
			if len(val) == 0 {
				return reflect.Zero(typ)
			}
			floatValue, err := strconv.ParseFloat(val, 64)
			if err != nil {
				binderLog.Warn("FloatBinder Conversion Error", "error", err)
				return reflect.Zero(typ)
			}
			pValue := reflect.New(typ)
			pValue.Elem().SetFloat(floatValue)
			return pValue.Elem()
		}),
		Unbind: func(output map[string]string, key string, val interface{}) {
			output[key] = fmt.Sprintf("%f", val)
		},
	}

	StringBinder = Binder{
		Bind: ValueBinder(func(val string, typ reflect.Type) reflect.Value {
			return reflect.ValueOf(val)
		}),
		Unbind: func(output map[string]string, name string, val interface{}) {
			if u, ok := val.(template.URL); ok {
				output[name] = string(u)
			} else {
				output[name] = val.(string)
			}
		},
	}

	// Booleans support a various value formats,
	// refer `revel.Atob` method.
	BoolBinder = Binder{
		Bind: ValueBinder(func(val string, typ reflect.Type) reflect.Value {
			return reflect.ValueOf(Atob(val))
		}),
		Unbind: func(output map[string]string, name string, val interface{}) {
			output[name] = fmt.Sprintf("%t", val)
		},
	}

	PointerBinder = Binder{
		Bind: func(params *Params, name string, typ reflect.Type) reflect.Value {
			v := Bind(params, name, typ.Elem())
			if v.CanAddr() {
				return v.Addr()
			}

			return v
		},
		Unbind: func(output map[string]string, name string, val interface{}) {
			Unbind(output, name, reflect.ValueOf(val).Elem().Interface())
		},
	}

	TimeBinder = Binder{
		Bind: ValueBinder(func(val string, typ reflect.Type) reflect.Value {
			for _, f := range TimeFormats {
				if r, err := time.ParseInLocation(f, val, TimeZone); err == nil {
					return reflect.ValueOf(r)
				}
			}
			return reflect.Zero(typ)
		}),
		Unbind: func(output map[string]string, name string, val interface{}) {
			var (
				t       = val.(time.Time)
				format  = DateTimeFormat
				h, m, s = t.Clock()
			)
			if h == 0 && m == 0 && s == 0 {
				format = DateFormat
			}
			output[name] = t.Format(format)
		},
	}

	MapBinder = Binder{
		Bind:   bindMap,
		Unbind: unbindMap,
	}
)

// Used to keep track of the index for individual keyvalues.
type sliceValue struct {
	index int           // Index extracted from brackets.  If -1, no index was provided.
	value reflect.Value // the bound value for this slice element.
}

// This function creates a slice of the given type, Binds each of the individual
// elements, and then sets them to their appropriate location in the slice.
// If elements are provided without an explicit index, they are added (in
// unspecified order) to the end of the slice.
func bindSlice(params *Params, name string, typ reflect.Type) reflect.Value {
	// Collect an array of slice elements with their indexes (and the max index).
	maxIndex := -1
	numNoIndex := 0
	sliceValues := []sliceValue{}

	// Factor out the common slice logic (between form values and files).
	processElement := func(key string, vals []string, files []*multipart.FileHeader) {
		if !strings.HasPrefix(key, name+"[") {
			return
		}

		// Extract the index, and the index where a sub-key starts. (e.g. field[0].subkey)
		index := -1
		leftBracket, rightBracket := len(name), strings.Index(key[len(name):], "]")+len(name)
		if rightBracket > leftBracket+1 {
			index, _ = strconv.Atoi(key[leftBracket+1 : rightBracket])
		}
		subKeyIndex := rightBracket + 1

		// Handle the indexed case.
		if index > -1 {
			if index > maxIndex {
				maxIndex = index
			}
			sliceValues = append(sliceValues, sliceValue{
				index: index,
				value: Bind(params, key[:subKeyIndex], typ.Elem()),
			})
			return
		}

		// It's an un-indexed element.  (e.g. element[])
		numNoIndex += len(vals) + len(files)
		for _, val := range vals {
			// Unindexed values can only be direct-bound.
			sliceValues = append(sliceValues, sliceValue{
				index: -1,
				value: BindValue(val, typ.Elem()),
			})
		}

		for _, fileHeader := range files {
			sliceValues = append(sliceValues, sliceValue{
				index: -1,
				value: BindFile(fileHeader, typ.Elem()),
			})
		}
	}

	for key, vals := range params.Values {
		processElement(key, vals, nil)
	}
	for key, fileHeaders := range params.Files {
		processElement(key, nil, fileHeaders)
	}

	resultArray := reflect.MakeSlice(typ, maxIndex+1, maxIndex+1+numNoIndex)
	for _, sv := range sliceValues {
		if sv.index != -1 {
			resultArray.Index(sv.index).Set(sv.value)
		} else {
			resultArray = reflect.Append(resultArray, sv.value)
		}
	}

	return resultArray
}

// Break on dots and brackets.
// e.g. bar => "bar", bar.baz => "bar", bar[0] => "bar"
func nextKey(key string) string {
	fieldLen := strings.IndexAny(key, ".[")
	if fieldLen == -1 {
		return key
	}
	return key[:fieldLen]
}

func unbindSlice(output map[string]string, name string, val interface{}) {
	v := reflect.ValueOf(val)
	for i := 0; i < v.Len(); i++ {
		Unbind(output, fmt.Sprintf("%s[%d]", name, i), v.Index(i).Interface())
	}
}

func bindStruct(params *Params, name string, typ reflect.Type) reflect.Value {
	resultPointer := reflect.New(typ)
	result := resultPointer.Elem()
	if params.JSON != nil {
		// Try to inject the response as a json into the created result
		if err := json.Unmarshal(params.JSON, resultPointer.Interface()); err != nil {
			binderLog.Error("bindStruct Unable to unmarshal request", "name", name, "error", err, "data", string(params.JSON))
		}
		return result
	}
	fieldValues := make(map[string]reflect.Value)
	for key := range params.Values {
		if !strings.HasPrefix(key, name+".") {
			continue
		}

		// Get the name of the struct property.
		// Strip off the prefix. e.g. foo.bar.baz => bar.baz
		suffix := key[len(name)+1:]
		fieldName := nextKey(suffix)
		fieldLen := len(fieldName)

		if _, ok := fieldValues[fieldName]; !ok {
			// Time to bind this field.  Get it and make sure we can set it.
			fieldValue := result.FieldByName(fieldName)
			if !fieldValue.IsValid() {
				binderLog.Warn("bindStruct Field not found", "name", fieldName)
				continue
			}
			if !fieldValue.CanSet() {
				binderLog.Warn("bindStruct Field not settable", "name", fieldName)
				continue
			}
			boundVal := Bind(params, key[:len(name)+1+fieldLen], fieldValue.Type())
			fieldValue.Set(boundVal)
			fieldValues[fieldName] = boundVal
		}
	}

	return result
}

func unbindStruct(output map[string]string, name string, iface interface{}) {
	val := reflect.ValueOf(iface)
	typ := val.Type()
	for i := 0; i < val.NumField(); i++ {
		structField := typ.Field(i)
		fieldValue := val.Field(i)

		// PkgPath is specified to be empty exactly for exported fields.
		if structField.PkgPath == "" {
			Unbind(output, fmt.Sprintf("%s.%s", name, structField.Name), fieldValue.Interface())
		}
	}
}

// Helper that returns an upload of the given name, or nil.
func getMultipartFile(params *Params, name string) multipart.File {
	for _, fileHeader := range params.Files[name] {
		file, err := fileHeader.Open()
		if err == nil {
			return file
		}
		binderLog.Warn("getMultipartFile: Failed to open uploaded file", "name", name, "error", err)
	}
	return nil
}

func bindFile(params *Params, name string, typ reflect.Type) reflect.Value {
	reader := getMultipartFile(params, name)
	if reader == nil {
		return reflect.Zero(typ)
	}

	// If it's already stored in a temp file, just return that.
	if osFile, ok := reader.(*os.File); ok {
		return reflect.ValueOf(osFile)
	}

	// Otherwise, have to store it.
	tmpFile, err := ioutil.TempFile("", "revel-upload")
	if err != nil {
		binderLog.Warn("bindFile: Failed to create a temp file to store upload", "name", name, "error", err)
		return reflect.Zero(typ)
	}

	// Register it to be deleted after the request is done.
	params.tmpFiles = append(params.tmpFiles, tmpFile)

	_, err = io.Copy(tmpFile, reader)
	if err != nil {
		binderLog.Warn("bindFile: Failed to copy upload to temp file", "name", name, "error", err)
		return reflect.Zero(typ)
	}

	_, err = tmpFile.Seek(0, 0)
	if err != nil {
		binderLog.Warn("bindFile: Failed to seek to beginning of temp file", "name", name, "error", err)
		return reflect.Zero(typ)
	}

	return reflect.ValueOf(tmpFile)
}

func bindByteArray(params *Params, name string, typ reflect.Type) reflect.Value {
	if reader := getMultipartFile(params, name); reader != nil {
		b, err := ioutil.ReadAll(reader)
		if err == nil {
			return reflect.ValueOf(b)
		}
		binderLog.Warn("bindByteArray: Error reading uploaded file contents", "name", name, "error", err)
	}
	return reflect.Zero(typ)
}

func bindReadSeeker(params *Params, name string, typ reflect.Type) reflect.Value {
	if reader := getMultipartFile(params, name); reader != nil {
		return reflect.ValueOf(reader.(io.ReadSeeker))
	}
	return reflect.Zero(typ)
}

// bindMap converts parameters using map syntax into the corresponding map. e.g.:
//   params["a[5]"]=foo, name="a", typ=map[int]string => map[int]string{5: "foo"}
func bindMap(params *Params, name string, typ reflect.Type) reflect.Value {
	var (
		keyType   = typ.Key()
		valueType = typ.Elem()
		resultPtr = reflect.New(reflect.MapOf(keyType, valueType))
		result    = resultPtr.Elem()
	)
	result.Set(reflect.MakeMap(typ))
	if params.JSON != nil {
		// Try to inject the response as a json into the created result
		if err := json.Unmarshal(params.JSON, resultPtr.Interface()); err != nil {
			binderLog.Warn("bindMap: Unable to unmarshal request", "name", name, "error", err)
		}
		return result
	}

	for paramName, values := range params.Values {
		// The paramName string must start with the value in the "name" parameter,
		// otherwise there is no way the parameter is part of the map
		if !strings.HasPrefix(paramName, name) {
			continue
		}

		var fieldName, suffix string

		if len(paramName) > len(name) {
			fieldName = paramName[len(name)+1:]
			fieldLen := -1
			switch paramName[len(name)] {
			case '[':
				fieldLen = strings.IndexByte(fieldName, ']')
			case '.':
				fieldLen = strings.IndexAny(fieldName, ".[")
			default:
				fieldLen = MaxInt
				break
			}
			if fieldLen == MaxInt {
				continue
			}

			if fieldLen > 0 {
				suffix = fieldName[fieldLen+1:]
				fieldName = fieldName[:fieldLen]
			}
		}

		if valueType.Kind() == reflect.Interface {
			if suffix == "[]" {
				result.SetMapIndex(BindValue(fieldName, keyType), reflect.ValueOf(values))
			} else if suffix == "" {
				result.SetMapIndex(BindValue(fieldName, keyType), reflect.ValueOf(values[0]))
			} else {
				newValueType := reflect.TypeOf((*map[string]interface{})(nil)).Elem()
				result.SetMapIndex(BindValue(fieldName, keyType), Bind(params, paramName[:len(paramName)-len(suffix)], newValueType))
			}
			continue
		}
		result.SetMapIndex(BindValue(fieldName, keyType), Bind(params, paramName[:len(paramName)-len(suffix)], valueType))
	}
	return result
}

func unbindMap(output map[string]string, name string, iface interface{}) {
	mapValue := reflect.ValueOf(iface)
	for _, key := range mapValue.MapKeys() {
		Unbind(output, name+"["+fmt.Sprintf("%v", key.Interface())+"]",
			mapValue.MapIndex(key).Interface())
	}
}

// Bind takes the name and type of the desired parameter and constructs it
// from one or more values from Params.
// Returns the zero value of the type upon any sort of failure.
func Bind(params *Params, name string, typ reflect.Type) reflect.Value {
	if binder, found := binderForType(typ); found {
		return binder.Bind(params, name, typ)
	}
	return reflect.Zero(typ)
}

func BindValue(val string, typ reflect.Type) reflect.Value {
	return Bind(&Params{Values: map[string][]string{"": {val}}}, "", typ)
}

func BindFile(fileHeader *multipart.FileHeader, typ reflect.Type) reflect.Value {
	return Bind(&Params{Files: map[string][]*multipart.FileHeader{"": {fileHeader}}}, "", typ)
}

func Unbind(output map[string]string, name string, val interface{}) {
	if binder, found := binderForType(reflect.TypeOf(val)); found {
		if binder.Unbind != nil {
			binder.Unbind(output, name, val)
		} else {
			binderLog.Error("Unbind: Unable to unmarshal request", "name", name, "value", val)
		}
	}
}

func binderForType(typ reflect.Type) (Binder, bool) {
	binder, ok := TypeBinders[typ]
	if !ok {
		binder, ok = KindBinders[typ.Kind()]
		if !ok {
			binderLog.Error("binderForType: no binder for type", "type", typ)
			return Binder{}, false
		}
	}
	return binder, true
}

// Sadly, the binder lookups can not be declared initialized -- that results in
// an "initialization loop" compile error.
func init() {
	KindBinders[reflect.Int] = IntBinder
	KindBinders[reflect.Int8] = IntBinder
	KindBinders[reflect.Int16] = IntBinder
	KindBinders[reflect.Int32] = IntBinder
	KindBinders[reflect.Int64] = IntBinder

	KindBinders[reflect.Uint] = UintBinder
	KindBinders[reflect.Uint8] = UintBinder
	KindBinders[reflect.Uint16] = UintBinder
	KindBinders[reflect.Uint32] = UintBinder
	KindBinders[reflect.Uint64] = UintBinder

	KindBinders[reflect.Float32] = FloatBinder
	KindBinders[reflect.Float64] = FloatBinder

	KindBinders[reflect.String] = StringBinder
	KindBinders[reflect.Bool] = BoolBinder
	KindBinders[reflect.Slice] = Binder{bindSlice, unbindSlice}
	KindBinders[reflect.Struct] = Binder{bindStruct, unbindStruct}
	KindBinders[reflect.Ptr] = PointerBinder
	KindBinders[reflect.Map] = MapBinder

	TypeBinders[reflect.TypeOf(time.Time{})] = TimeBinder

	// Uploads
	TypeBinders[reflect.TypeOf(&os.File{})] = Binder{bindFile, nil}
	TypeBinders[reflect.TypeOf([]byte{})] = Binder{bindByteArray, nil}
	TypeBinders[reflect.TypeOf((*io.Reader)(nil)).Elem()] = Binder{bindReadSeeker, nil}
	TypeBinders[reflect.TypeOf((*io.ReadSeeker)(nil)).Elem()] = Binder{bindReadSeeker, nil}

	OnAppStart(func() {
		DateTimeFormat = Config.StringDefault("format.datetime", DefaultDateTimeFormat)
		DateFormat = Config.StringDefault("format.date", DefaultDateFormat)
		TimeFormats = append(TimeFormats, DateTimeFormat, DateFormat)
	})
}


text:
package com.rhinoforms.util;

import java.util.Collections;
import java.util.Enumeration;
import java.util.LinkedHashSet;
import java.util.Properties;
import java.util.Set;

public class LinkedProperties extends Properties {

	private static final long serialVersionUID = 6565227944227691622L;
	private final LinkedHashSet<Object> keys = new LinkedHashSet<Object>();

	@Override
	public Enumeration<Object> keys() {
		return Collections.<Object> enumeration(keys);
	}

	@Override
	public Set<Object> keySet() {
		return keys;
	}

	@Override
	public Object put(Object key, Object value) {
		keys.add(key);
		return super.put(key, value);
	}

}

redpajama_set_name: RedPajamaGithub


text:
from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = []

    operations = [
        migrations.CreateModel(
            name="Form",
            fields=[
                (
                    "id",
                    models.AutoField(
                        primary_key=True,
                        serialize=False,
                        verbose_name="ID",
                        auto_created=True,
                    ),
                ),
                ("title", models.CharField(verbose_name="title", max_length=100)),
                ("config_json", models.TextField(verbose_name="config", blank=True)),
            ],
            options={"verbose_name": "form", "verbose_name_plural": "forms"},
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name="FormField",
            fields=[
                (
                    "id",
                    models.AutoField(
                        primary_key=True,
                        serialize=False,
                        verbose_name="ID",
                        auto_created=True,
                    ),
                ),
                ("ordering", models.IntegerField(default=0, verbose_name="ordering")),
                ("title", models.CharField(verbose_name="field title", max_length=100)),
                ("name", models.CharField(verbose_name="field name", max_length=100)),
                (
                    "type",
                    models.CharField(
                        verbose_name="field type", choices=[("", "")], max_length=20
                    ),
                ),
                (
                    "choices",
                    models.CharField(
                        verbose_name="choices",
                        help_text="Comma-separated",
                        blank=True,
                        max_length=1024,
                    ),
                ),
                (
                    "help_text",
                    models.CharField(
                        verbose_name="help text",
                        help_text="Optional extra explanatory text beside the field",
                        blank=True,
                        max_length=1024,
                    ),
                ),
                (
                    "default_value",
                    models.CharField(
                        verbose_name="default value",
                        help_text="Optional default value of the field",
                        blank=True,
                        max_length=255,
                    ),
                ),
                (
                    "is_required",
                    models.BooleanField(default=True, verbose_name="is required"),
                ),
                (
                    "form",
                    models.ForeignKey(
                        related_name="fields",
                        verbose_name="form",
                        to="form_designer.Form",
                        on_delete=models.CASCADE,
                    ),
                ),
            ],
            options={
                "ordering": ["ordering", "id"],
                "verbose_name": "form field",
                "verbose_name_plural": "form fields",
            },
            bases=(models.Model,),
        ),
        migrations.AlterUniqueTogether(
            name="formfield", unique_together={("form", "name")}
        ),
        migrations.CreateModel(
            name="FormSubmission",
            fields=[
                (
                    "id",
                    models.AutoField(
                        primary_key=True,
                        serialize=False,
                        verbose_name="ID",
                        auto_created=True,
                    ),
                ),
                ("submitted", models.DateTimeField(auto_now_add=True)),
                ("data", models.TextField()),
                ("path", models.CharField(max_length=255)),
                (
                    "form",
                    models.ForeignKey(
                        related_name="submissions",
                        verbose_name="form",
                        to="form_designer.Form",
                        on_delete=models.CASCADE,
                    ),
                ),
            ],
            options={
                "ordering": ("-submitted",),
                "verbose_name": "form submission",
                "verbose_name_plural": "form submissions",
            },
            bases=(models.Model,),
        ),
    ]


text:
'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
	Schema = mongoose.Schema;

/**
 * Streak Schema
 */
var StreakSchema = new Schema({
	name: {
		type: String,
		default: '',
		required: 'Please fill Streak name',
		trim: true
	},
	short_description: {
		type: String,
		default: '',
		required: 'Please fill description',
		trim: true
	},
	order: {
		type: Number,
		default: 0
	},
	Number: {
		type: Number,
		default: 0
	},
	reviewed: {
		type: Boolean,
		default: false
	},
	is_visible: {
		type: Boolean,
		default: false
	},
	created: {
		type: Date,
		default: Date.now
	},
	user: {
		type: Schema.ObjectId,
		ref: 'User'
	}
});

mongoose.model('Streak', StreakSchema);


text:
package com.navercorp.pinpoint.profiler.context.provider;

import com.google.inject.Inject;
import com.google.inject.Provider;
import com.navercorp.pinpoint.bootstrap.config.ProfilerConfig;
import com.navercorp.pinpoint.bootstrap.instrument.DynamicTransformTrigger;
import com.navercorp.pinpoint.profiler.instrument.InstrumentEngine;
import com.navercorp.pinpoint.profiler.context.module.PluginJars;
import com.navercorp.pinpoint.profiler.plugin.DefaultPluginContextLoadResult;
import com.navercorp.pinpoint.profiler.plugin.PluginContextLoadResult;

import java.net.URL;

/**
 * @author Woonduk Kang(emeroad)
 */
public class PluginContextLoadResultProvider implements Provider<PluginContextLoadResult> {

    private final ProfilerConfig profilerConfig;
    private final InstrumentEngine instrumentEngine;
    private final URL[] pluginJars;
    private final DynamicTransformTrigger dynamicTransformTrigger;

    @Inject
    public PluginContextLoadResultProvider(ProfilerConfig profilerConfig, DynamicTransformTrigger dynamicTransformTrigger, InstrumentEngine instrumentEngine,
                                           @PluginJars URL[] pluginJars) {
        if (profilerConfig == null) {
            throw new NullPointerException("profilerConfig must not be null");
        }
        if (dynamicTransformTrigger == null) {
            throw new NullPointerException("dynamicTransformTrigger must not be null");
        }
        if (instrumentEngine == null) {
            throw new NullPointerException("instrumentEngine must not be null");
        }
        if (pluginJars == null) {
            throw new NullPointerException("pluginJars must not be null");
        }

        this.profilerConfig = profilerConfig;
        this.dynamicTransformTrigger = dynamicTransformTrigger;

        this.instrumentEngine = instrumentEngine;
        this.pluginJars = pluginJars;
    }

    @Override
    public PluginContextLoadResult get() {
        return new DefaultPluginContextLoadResult(profilerConfig, dynamicTransformTrigger, instrumentEngine, pluginJars);

    }
}


text:
#include "condor_common.h"
#include "condor_config.h"
#include "ccb_listener.h"
#include "subsystem_info.h"

static const int CCB_TIMEOUT = 300;

CCBListener::CCBListener(char const *ccb_address):
	m_ccb_address(ccb_address),
	m_sock(NULL),
	m_waiting_for_connect(false),
	m_waiting_for_registration(false),
	m_registered(false),
	m_reconnect_timer(-1),
	m_heartbeat_timer(-1),
	m_heartbeat_interval(0),
	m_last_contact_from_peer(0),
	m_heartbeat_disabled(false),
	m_heartbeat_initialized(false)
{
}

CCBListener::~CCBListener()
{
	if( m_sock ) {
		daemonCore->Cancel_Socket( m_sock );
		delete m_sock;
	}
	if( m_reconnect_timer != -1 ) {
		daemonCore->Cancel_Timer( m_reconnect_timer );
	}
	StopHeartbeat();
}

void
CCBListener::InitAndReconfig()
{
	int new_heartbeat_interval = param_integer("CCB_HEARTBEAT_INTERVAL",1200,0);
	if( new_heartbeat_interval != m_heartbeat_interval ) {
		if( new_heartbeat_interval < 30 && new_heartbeat_interval > 0 ) {
			new_heartbeat_interval = 30;
				// CCB server doesn't expect a high rate of unsolicited
				// input from us
			dprintf(D_ALWAYS,
					"CCBListener: using minimum heartbeat interval of %ds\n",
					new_heartbeat_interval);
		}
		m_heartbeat_interval = new_heartbeat_interval;
		if( m_heartbeat_initialized ) {
			RescheduleHeartbeat();
		}
	}
}

bool
CCBListener::RegisterWithCCBServer(bool blocking)
{
	ClassAd msg;

	if( m_waiting_for_connect || m_reconnect_timer != -1 || m_waiting_for_registration || m_registered) {
			// already registered or being registered
		return m_registered;
	}

	msg.Assign( ATTR_COMMAND, CCB_REGISTER );
	if( !m_ccbid.IsEmpty() ) {
		// we are reconnecting; trying to preserve ccbid so that prospective
		// clients with stale information can still contact us
		msg.Assign( ATTR_CCBID, m_ccbid.Value() );
		msg.Assign( ATTR_CLAIM_ID, m_reconnect_cookie.Value() );
	}

		// for debugging purposes only, identify ourselves to the CCB server
	MyString name;
	name.sprintf("%s %s",get_mySubSystem()->getName(),daemonCore->publicNetworkIpAddr());
	msg.Assign( ATTR_NAME, name.Value() );

	bool success = SendMsgToCCB(msg,blocking);
	if( success ) {
		if( blocking ) {
			success = ReadMsgFromCCB();
		}
		else {
			// now we wait for CCB server to respond with our CCBID
			m_waiting_for_registration = true;
		}
	}
	return success;
}

bool
CCBListener::SendMsgToCCB(ClassAd &msg,bool blocking)
{
	if( !m_sock ) {
		Daemon ccb(DT_COLLECTOR,m_ccb_address.Value());

		int cmd = -1;
		msg.LookupInteger( ATTR_COMMAND, cmd );
		if( cmd != CCB_REGISTER ) {
			dprintf(D_ALWAYS,"CCBListener: no connection to CCB server %s"
					" when trying to send command %d\n",
					m_ccb_address.Value(), cmd );
			return false;
		}

		// Specifying USE_TMP_SEC_SESSION to force a fresh security
		// session.  Otherwise we can end up in a catch-22 where we
		// are trying to reconnect to the CCB server and we try to use
		// a cached security session which is no longer valid, but our
		// CCB server cannot send us the invalidation message because
		// we are trying to reconnect to it.  Expring this session
		// right away is also a good idea, because if we are just
		// starting up, the return address associated with it will not
		// have any CCB information attached, which again means that
		// the CCB server has no way to invalidate it.

		if( blocking ) {
			m_sock = ccb.startCommand( cmd, Stream::reli_sock, CCB_TIMEOUT, NULL, NULL, false, USE_TMP_SEC_SESSION );
			if( m_sock ) {
				Connected();
			}
			else {
				Disconnected();
				return false;
			}
		}
		else if( !m_waiting_for_connect ) {
			m_sock = ccb.makeConnectedSocket(Stream::reli_sock, CCB_TIMEOUT, 0, NULL, true /*nonblocking*/ );
			if( !m_sock ) {
				Disconnected();
				return false;
			}
			m_waiting_for_connect = true;
			incRefCount(); // do not let ourselves be deleted until called back
			ccb.startCommand_nonblocking( cmd, m_sock, CCB_TIMEOUT, NULL, CCBListener::CCBConnectCallback, this, NULL, false, USE_TMP_SEC_SESSION );
			return false;
		}
	}

	return WriteMsgToCCB(msg);
}

bool
CCBListener::WriteMsgToCCB(ClassAd &msg)
{
	if( !m_sock ) {
		return false;
	}

	m_sock->encode();
	if( !msg.put( *m_sock ) || !m_sock->end_of_message() ) {
		Disconnected();
		return false;
	}

	return true;
}

void
CCBListener::CCBConnectCallback(bool success,Sock *sock,CondorError * /*errstack*/,void *misc_data)
{
	CCBListener *self = (CCBListener *)misc_data;

	self->m_waiting_for_connect = false;

	ASSERT( self->m_sock == sock );

	if( success ) {
		ASSERT( self->m_sock->is_connected() );
		self->Connected();
		self->RegisterWithCCBServer();
	}
	else {
		delete self->m_sock;
		self->m_sock = NULL;
		self->Disconnected();
	}

	self->decRefCount(); // remove ref count from when we started the connect
}

void
CCBListener::ReconnectTime()
{
	m_reconnect_timer = -1;

	RegisterWithCCBServer();
}

void
CCBListener::Connected()
{
	int rc = daemonCore->Register_Socket(
		m_sock,
		m_sock->peer_description(),
		(SocketHandlercpp)&CCBListener::HandleCCBMsg,
		"CCBListener::HandleCCBMsg",
		this);

	ASSERT( rc >= 0 );

	m_last_contact_from_peer = time(NULL);
	RescheduleHeartbeat();
}

void
CCBListener::Disconnected()
{
	if( m_sock ) {
		daemonCore->Cancel_Socket( m_sock );
		delete m_sock;
		m_sock = NULL;
	}

	m_waiting_for_registration = false;
	m_registered = false;

	StopHeartbeat();

	if( m_reconnect_timer != -1 ) {
		return; // already in progress
	}

	int reconnect_time = param_integer("CCB_RECONNECT_TIME",60);

	dprintf(D_ALWAYS,
			"CCBListener: connection to CCB server %s failed; "
			"will try to reconnect in %d seconds.\n",
			m_ccb_address.Value(), reconnect_time);

	m_reconnect_timer = daemonCore->Register_Timer(
		reconnect_time,
		(TimerHandlercpp)&CCBListener::ReconnectTime,
		"CCBListener::ReconnectTime",
		this );

	ASSERT( m_reconnect_timer != -1 );
}

void
CCBListener::StopHeartbeat()
{
	if( m_heartbeat_timer != -1 ) {
		daemonCore->Cancel_Timer( m_heartbeat_timer );
		m_heartbeat_timer = -1;
	}
}

void
CCBListener::RescheduleHeartbeat()
{
	if( !m_heartbeat_initialized ) {
		if( !m_sock ) {
			return;
		}

		m_heartbeat_initialized = true;

		m_heartbeat_disabled = false;
		CondorVersionInfo const *server_version = m_sock->get_peer_version();
		if( m_heartbeat_interval <= 0 ) {
			dprintf(D_ALWAYS,"CCBListener: heartbeat disabled because interval is configured to be 0\n");
		}
		else if( server_version ) {
			if( !server_version->built_since_version(7,5,0) ) {
				m_heartbeat_disabled = true;
				dprintf(D_ALWAYS,"CCBListener: server is too old to support heartbeat, so not sending one.\n");
			}
		}
	}

	if( m_heartbeat_interval <= 0 || m_heartbeat_disabled ) {
		StopHeartbeat();
		m_heartbeat_initialized = true;
	}
	else if( m_sock && m_sock->is_connected() ) {
		int next_time = m_heartbeat_interval - (time(NULL)-m_last_contact_from_peer);
		if( next_time < 0 || next_time > m_heartbeat_interval) {
			next_time = 0;
		}
		if( m_heartbeat_timer == -1 ) {
			m_last_contact_from_peer = time(NULL);
			m_heartbeat_timer = daemonCore->Register_Timer(
				next_time,
				m_heartbeat_interval,
				(TimerHandlercpp)&CCBListener::HeartbeatTime,
				"CCBListener::HeartbeatTime",
				this );
			ASSERT( m_heartbeat_timer != -1 );
		}
		else {
			daemonCore->Reset_Timer(
				m_heartbeat_timer,
				next_time,
				m_heartbeat_interval);
		}
	}
}

void
CCBListener::HeartbeatTime()
{
	int age = time(NULL) - m_last_contact_from_peer;
	if( age > 3*m_heartbeat_interval ) {
		dprintf(D_ALWAYS, "CCBListener: no activity from CCB server in %ds; "
				"assuming connection is dead.\n", age);
		Disconnected();
		return;
	}

	dprintf(D_FULLDEBUG, "CCBListener: sent heartbeat to server.\n");

	ClassAd msg;
	msg.Assign(ATTR_COMMAND, ALIVE);
	SendMsgToCCB(msg,false);
}

int
CCBListener::HandleCCBMsg(Stream * /*sock*/)
{
	ReadMsgFromCCB();
	return KEEP_STREAM;
}

bool
CCBListener::ReadMsgFromCCB()
{
	if( !m_sock ) {
		return false;
	}
	m_sock->timeout(CCB_TIMEOUT);
	ClassAd msg;
	if( !msg.initFromStream( *m_sock ) || !m_sock->end_of_message() ) {
		dprintf(D_ALWAYS,
				"CCBListener: failed to receive message from CCB server %s\n",
				m_ccb_address.Value());
		Disconnected();
		return false;
	}

	m_last_contact_from_peer = time(NULL);
	RescheduleHeartbeat();

	int cmd = -1;
	msg.LookupInteger( ATTR_COMMAND, cmd );
	switch( cmd ) {
	case CCB_REGISTER:
		return HandleCCBRegistrationReply( msg );
	case CCB_REQUEST:
		return HandleCCBRequest( msg );
	case ALIVE:
		dprintf(D_FULLDEBUG,"CCBListener: received heartbeat from server.\n");
		return true;
	}

	MyString msg_str;
	msg.sPrint(msg_str);
	dprintf( D_ALWAYS,
			 "CCBListener: Unexpected message received from CCB "
			 "server: %s\n",
			 msg_str.Value() );
	return false;
}

bool
CCBListener::HandleCCBRegistrationReply( ClassAd &msg )
{
	if( !msg.LookupString(ATTR_CCBID,m_ccbid) ) {
		MyString msg_str;
		msg.sPrint(msg_str);
		EXCEPT("CCBListener: no ccbid in registration reply: %s\n",
			   msg_str.Value() );
	}
	msg.LookupString(ATTR_CLAIM_ID,m_reconnect_cookie);
	dprintf(D_ALWAYS,
			"CCBListener: registered with CCB server %s as ccbid %s\n",
			m_ccb_address.Value(),
			m_ccbid.Value() );

	m_waiting_for_registration = false;
	m_registered = true;

	daemonCore->daemonContactInfoChanged();

	return true;
}

bool
CCBListener::HandleCCBRequest( ClassAd &msg )
{
	MyString address;
	MyString connect_id;
	MyString request_id;
	MyString name;
	if( !msg.LookupString( ATTR_MY_ADDRESS, address) ||
		!msg.LookupString( ATTR_CLAIM_ID, connect_id) ||
		!msg.LookupString( ATTR_REQUEST_ID, request_id) )
	{
		MyString msg_str;
		msg.sPrint(msg_str);
		EXCEPT("CCBListener: invalid CCB request from %s: %s\n",
			   m_ccb_address.Value(),
			   msg_str.Value() );
	}

	msg.LookupString( ATTR_NAME, name );

	if( name.find(address.Value())<0 ) {
		name.sprintf_cat(" with reverse connect address %s",address.Value());
	}
	dprintf(D_FULLDEBUG|D_NETWORK,
			"CCBListener: received request to connect to %s, request id %s.\n",
			name.Value(), request_id.Value());

	return DoReversedCCBConnect( address.Value(), connect_id.Value(), request_id.Value(), name.Value() );
}

bool
CCBListener::DoReversedCCBConnect( char const *address, char const *connect_id, char const *request_id, char const *peer_description )
{
	Daemon daemon( DT_ANY, address );
	CondorError errstack;
	Sock *sock = daemon.makeConnectedSocket(
		Stream::reli_sock,CCB_TIMEOUT,0,&errstack,true /*nonblocking*/);

	ClassAd *msg_ad = new ClassAd;
	ASSERT( msg_ad );
	msg_ad->Assign( ATTR_CLAIM_ID, connect_id );
	msg_ad->Assign( ATTR_REQUEST_ID, request_id );
		// the following is put in the message because that is an easy (lazy)
		// way to make it available to ReportReverseConnectResult
	msg_ad->Assign( ATTR_MY_ADDRESS, address);

	if( !sock ) {
			// Failed to create socket or initiate connect
		ReportReverseConnectResult(msg_ad,false,"failed to initiate connection");
		delete msg_ad;
		return false;
	}

	if( peer_description ) {
		char const *peer_ip = sock->peer_ip_str();
		if( peer_ip && !strstr(peer_description,peer_ip)) {
			MyString desc;
			desc.sprintf("%s at %s",peer_description,sock->get_sinful_peer());
			sock->set_peer_description(desc.Value());
		}
		else {
			sock->set_peer_description(peer_description);
		}
	}

	incRefCount();      // do not delete self until called back

	MyString sock_desc;
	int rc = daemonCore->Register_Socket(
		sock,
		sock->peer_description(),
		(SocketHandlercpp)&CCBListener::ReverseConnected,
		"CCBListener::ReverseConnected",
		this);

	if( rc < 0 ) {
		ReportReverseConnectResult(msg_ad,false,"failed to register socket for non-blocking reversed connection");
		delete msg_ad;
		delete sock;
		decRefCount();
		return false;
	}

	rc = daemonCore->Register_DataPtr(msg_ad);
	ASSERT( rc );

	return true;
}

int
CCBListener::ReverseConnected(Stream *stream)
{
	Sock *sock = (Sock *)stream;
	ClassAd *msg_ad = (ClassAd *)daemonCore->GetDataPtr();
	ASSERT( msg_ad );

	if( sock ) {
		daemonCore->Cancel_Socket( sock );
	}

	if( !sock || !sock->is_connected() ) {
		ReportReverseConnectResult(msg_ad,false,"failed to connect");
	}
	else {

			// The reverse-connect protocol is designed to look like a
			// raw cedar command, in case the thing we are connecting
			// to is a cedar command socket.

		sock->encode();
		int cmd = CCB_REVERSE_CONNECT;
		if( !sock->put(cmd) ||
			!msg_ad->put( *sock ) ||
			!sock->end_of_message() )
		{
			ReportReverseConnectResult(msg_ad,false,"failure writing reverse connect command");
		}
		else {
			((ReliSock*)sock)->isClient(false);
			daemonCore->HandleReqAsync(sock);
			sock = NULL; // daemonCore took ownership of sock
			ReportReverseConnectResult(msg_ad,true);
		}
	}

	delete msg_ad;
	if( sock ) {
		delete sock;
	}
	decRefCount(); // we incremented ref count when setting up callback

	return KEEP_STREAM;
}

void
CCBListener::ReportReverseConnectResult(ClassAd *connect_msg,bool success,char const *error_msg)
{
	ClassAd msg = *connect_msg;

	MyString request_id;
	MyString address;
	connect_msg->LookupString(ATTR_REQUEST_ID,request_id);
	connect_msg->LookupString(ATTR_MY_ADDRESS,address);
	if( !success ) {
		dprintf(D_ALWAYS,
				"CCBListener: failed to create reversed connection for "
				"request id %s to %s: %s\n",
				request_id.Value(),
				address.Value(),
				error_msg ? error_msg : "");
	}
	else {
		dprintf(D_FULLDEBUG|D_NETWORK,
				"CCBListener: created reversed connection for "
				"request id %s to %s: %s\n",
				request_id.Value(),
				address.Value(),
				error_msg ? error_msg : "");
	}

	msg.Assign(ATTR_RESULT,success);
	if( error_msg ) {
		msg.Assign(ATTR_ERROR_STRING,error_msg);
	}
	WriteMsgToCCB( msg );
}

bool
CCBListener::operator ==(CCBListener const &other)
{
	char const *other_addr = other.getAddress();
	if( m_ccb_address.Value() == other_addr ) {
		return true;
	}
	return other_addr && !strcmp(m_ccb_address.Value(),other_addr);
}

CCBListener *
CCBListeners::GetCCBListener(char const *address)
{
	classy_counted_ptr<CCBListener> ccb_listener;

	if( !address ) {
		return NULL;
	}

	m_ccb_listeners.Rewind();
	while( m_ccb_listeners.Next(ccb_listener) ) {
		if( !strcmp(address,ccb_listener->getAddress()) ) {
			return ccb_listener.get();
		}
	}
	return NULL;
}

void
CCBListeners::GetCCBContactString(MyString &result)
{
	classy_counted_ptr<CCBListener> ccb_listener;

	m_ccb_listeners.Rewind();
	while( m_ccb_listeners.Next(ccb_listener) ) {
		char const *ccbid = ccb_listener->getCCBID();
		if( ccbid && *ccbid ) {
			if( !result.IsEmpty() ) {
				result += " ";
			}
			result += ccbid;
		}
	}
}

bool
CCBListeners::RegisterWithCCBServer(bool blocking)
{
	bool result = true;

	classy_counted_ptr<CCBListener> ccb_listener;

	m_ccb_listeners.Rewind();
	while( m_ccb_listeners.Next(ccb_listener) ) {
		if( !ccb_listener->RegisterWithCCBServer(blocking) && blocking ) {
			result = false;
		}
	}
	return result;
}

void
CCBListeners::Configure(char const *addresses)
{
	StringList addrlist(addresses," ,");

	SimpleList< classy_counted_ptr<CCBListener> > new_ccbs;

	char const *address;
	addrlist.rewind();
	while( (address=addrlist.next()) ) {
		CCBListener *listener;

			// preserve existing CCBListener if there is one connected
			// to this address
		listener = GetCCBListener( address );

		if( !listener ) {

			Daemon daemon(DT_COLLECTOR,address);
			char const *ccb_addr_str = daemon.addr();
			char const *my_addr_str = daemonCore->publicNetworkIpAddr();
			Sinful ccb_addr( ccb_addr_str );
			Sinful my_addr( my_addr_str );

			if( my_addr.addressPointsToMe( ccb_addr ) ) {
				dprintf(D_ALWAYS,"CCBListener: skipping CCB Server %s because it points to myself.\n",address);
				continue;
			}
			dprintf(D_FULLDEBUG,"CCBListener: good: CCB address %s does not point to my address %s\n",
					ccb_addr_str?ccb_addr_str:"null",
					my_addr_str?my_addr_str:"null");

			listener = new CCBListener(address);
		}

		new_ccbs.Append( listener );
	}

	m_ccb_listeners.Clear();
	classy_counted_ptr<CCBListener> ccb_listener;

	new_ccbs.Rewind();
	while( new_ccbs.Next(ccb_listener) ) {
		if( GetCCBListener( ccb_listener->getAddress() ) ) {
				// ignore duplicate entries with same address
			continue;
		}
		m_ccb_listeners.Append( ccb_listener );

		ccb_listener->InitAndReconfig();
	}
}


text:
#ifndef CGI_H
#define CGI_H

int ICACHE_FLASH_ATTR cgiJson(HttpdConnData *connData);
int ICACHE_FLASH_ATTR cgiApi(HttpdConnData *connData);

#endif /* CGI_H */


text:
id: nativemodulesios
title: Native Modules (iOS)
layout: docs
category: Guides
permalink: docs/nativemodulesios.html
next: linking-libraries
---

Sometimes an app needs access to platform API, and React Native doesn't have a corresponding wrapper yet. Maybe you want to reuse some existing Objective-C or C++ code without having to reimplement it in JavaScript. Or write some high performance, multi-threaded code such as image processing, network stack, database or rendering.

We designed React Native such that it is possible for you to write real native code and have access to the full power of the platform. This is a more advanced feature and we don't expect it to be part of the usual development process, however it is essential that it exists. If React Native doesn't support a native feature that you need, you should be able to build it yourself.

This is a more advanced guide that shows how to build a native module. It assumes the reader knows Objective-C (Swift is not supported yet) and core libraries (Foundation, UIKit).

## iOS Calendar module example

This guide will use [iOS Calendar API](https://developer.apple.com/library/mac/documentation/DataManagement/Conceptual/EventKitProgGuide/Introduction/Introduction.html) example. Let's say we would like to be able to access iOS calendar from JavaScript.

Native module is just an Objectve-C class that implements `RCTBridgeModule` protocol. If you are wondering, RCT is a shorthand for ReaCT.

```objective-c
// CalendarManager.h
#import "RCTBridgeModule.h"
#import "RCTLog.h"

@interface CalendarManager : NSObject <RCTBridgeModule>
@end
```

React Native will not expose any methods of `CalendarManager` to JavaScript unless explicitly asked. Fortunately this is pretty easy with `RCT_EXPORT`:

```objective-c
// CalendarManager.m
@implementation CalendarManager

- (void)addEventWithName:(NSString *)name location:(NSString *)location
{
  RCT_EXPORT();
  RCTLogInfo(@"Pretending to create an event %@ at %@", name, location);
}

@end
```

Now from your JavaScript file you can call the method like this:

```javascript
var CalendarManager = require('NativeModules').CalendarManager;
CalendarManager.addEventWithName('Birthday Party', '4 Privet Drive, Surrey');
```

Notice that the exported method name was generated from first part of Objective-C selector. Sometimes it results in a non-idiomatic JavaScript name (like the one in our example). You can change the name by supplying an optional argument to `RCT_EXPORT`, e.g. `RCT_EXPORT(addEvent)`.

The return type of the method should always be `void`. React Native bridge is asynchronous, so the only way to pass result to JavaScript is by using callbacks or emitting events (see below).

## Argument types

React Native supports several types of arguments that can be passed from JavaScript code to native module:

- string (`NSString`)
- number (`NSInteger`, `float`, `double`, `CGFloat`, `NSNumber`)
- boolean (`BOOL`, `NSNumber`)
- array (`NSArray`) of any types from this list
- map (`NSDictionary`) with string keys and values of any type from this list
- function (`RCTResponseSenderBlock`)

In our `CalendarManager` example, if we want to pass event date to native, we have to convert it to a string or a number:

```objective-c
- (void)addEventWithName:(NSString *)name location:(NSString *)location date:(NSInteger)secondsSinceUnixEpoch
{
  RCT_EXPORT(addEvent);
  NSDate *date = [NSDate dateWithTimeIntervalSince1970:secondsSinceUnixEpoch];
}
```

As `CalendarManager.addEvent` method gets more and more complex, the number of arguments will grow. Some of them might be optional. In this case it's worth considering changing the API a little bit to accept a dictionary of event attributes, like this:

```objective-c
- (void)addEventWithName:(NSString *)name details:(NSDictionary *)details
{
  RCT_EXPORT(addEvent);
  NSString *location = [RCTConvert NSString:details[@"location"]]; // ensure location is a string
  ...
}
```

and call it from JavaScript:

```javascript
CalendarManager.addEvent('Birthday Party', {
  location: '4 Privet Drive, Surrey',
  time: date.toTime(),
  description: '...'
})
```

> **NOTE**: About array and map
>
> React Native doesn't provide any guarantees about the types of values in these structures. Your native module might expect array of strings, but if JavaScript calls your method with an array that contains number and string you'll get `NSArray` with `NSNumber` and `NSString`. It's the developer's responsibility to check array/map values types (see [`RCTConvert`](https://github.com/facebook/react-native/blob/master/React/Base/RCTConvert.h) for helper methods).

# Callbacks

> **WARNING**
>
> This section is even more experimental than others, we don't have a set of best practices around callbacks yet.

Native module also supports a special kind of argument - callback. In most cases it is used to provide function call result to JavaScript.

```objective-c
- (void)findEvents:(RCTResponseSenderBlock)callback
{
  RCT_EXPORT();
  NSArray *events = ...
  callback(@[[NSNull null], events]);
}
```

`RCTResponseSenderBlock` accepts only one argument - array of arguments to pass to JavaScript callback. In this case we use node's convention to set first argument to error and the rest - to the result of the function.

```javascript
CalendarManager.findEvents((error, events) => {
  if (error) {
    console.error(error);
  } else {
    this.setState({events: events});
  }
})
```

Native module is supposed to invoke callback only once. It can, however, store the callback as an ivar and invoke it later. This pattern is often used to wrap iOS APIs that require delegate. See [`RCTAlertManager`](https://github.com/facebook/react-native/blob/master/React/Modules/RCTAlertManager.m).

If you want to pass error-like object to JavaScript, use `RCTMakeError` from [`RCTUtils.h`](https://github.com/facebook/react-native/blob/master/React/Base/RCTUtils.h).

## Implementing native module

The native module should not have any assumptions about what thread it is being called on. React Native invokes native modules methods on a separate serial GCD queue, but this is an implementation detail and might change. If the native module needs to call main-thread-only iOS API, it should schedule the operation on the main queue:

```objective-c
- (void)addEventWithName:(NSString *)name callback:(RCTResponseSenderBlock)callback
{
  RCT_EXPORT(addEvent);
  dispatch_async(dispatch_get_main_queue(), ^{
    // Call iOS API on main thread
    ...
    // You can invoke callback from any thread/queue
    callback(@[...]);
  });
}
```

The same way if the operation can take a long time to complete, the native module should not block. It is a good idea to use `dispatch_async` to schedule expensive work on background queue.

## Exporting constants

Native module can export constants that are instantly available to JavaScript at runtime. This is useful to export some initial data that would otherwise require a bridge round-trip.

```objective-c
- (NSDictionary *)constantsToExport
{
  return @{ @"firstDayOfTheWeek": @"Monday" };
}
```

JavaScript can use this value right away:

```javascript
console.log(CalendarManager.firstDayOfTheWeek);
```

Note that the constants are exported only at initialization time, so if you change `constantsToExport` value at runtime it won't affect JavaScript environment.

## Sending events to JavaScript

The native module can signal events to JavaScript without being invoked directly. The easiest way to do this is to use `eventDispatcher`:

```objective-c
#import "RCTBridge.h"
#import "RCTEventDispatcher.h"

@implementation CalendarManager

@synthesize bridge = _bridge;

- (void)calendarEventReminderReceived:(NSNotification *)notification
{
  NSString *eventName = notification.userInfo[@"name"];
  [self.bridge.eventDispatcher sendAppEventWithName:@"EventReminder"
                                               body:@{@"name": eventName}];
}

@end
```

JavaScript code can subscribe to these events:

```javascript
var subscription = DeviceEventEmitter.addListener(
  'EventReminder',
  (reminder) => console.log(reminder.name)
);
...
// Don't forget to unsubscribe
subscription.remove();
```
For more examples of sending events to JavaScript, see [`RCTLocationObserver`](https://github.com/facebook/react-native/blob/master/Libraries/Geolocation/RCTLocationObserver.m).


text:
<link rel="import" href="scroll-animation.html">
<link rel="import" href="roll-up-animation.html">
<link rel="import" href="unroll-animation.html">


text:
const Path = require('path');
const Fs = require('fs');
const QConfig = require('qnode-config');
const MockConfigProvider = require('../MockConfigProvider');

const _CONFIG_FILE_NAME = 'mw';

module.exports = class MockConfigProvider_dir extends MockConfigProvider {

    resolveMockDir() {
        let r = this._config.dir;
        if (!r) r = Path.join(Path.dirname(require.main.filename), '../mock');
        return r;
    }

    load() {

        let dir = this.resolveMockDir();
        try {
            Fs.statSync(dir);
        } catch (e) {
            this._logger.warn(`mock directory is not found: ${dir}`);
            return {};
        }

        const r = {};

        /* eslint no-sync: "off" */
        for (const fileName of Fs.readdirSync(dir)) {
            const server = this.loadServerByPort(Path.join(dir, fileName));
            if (!server) continue;

            r[server.port] = server;
        }

        return r;
    }

    loadServerByPort(dir) {
        /* eslint no-sync: "off" */
        const stat = Fs.statSync(dir);
        if (!stat.isDirectory()) return undefined;

        let port = parseInt(Path.basename(dir), 10);
        if (isNaN(port)) return undefined;

        const vhosts = {};

        /* eslint no-sync: "off" */
        for (const fileName of Fs.readdirSync(dir)) {
            const vhost = this.loadVirtualHost(Path.join(dir, fileName));
            if (!vhost) continue;

            vhosts[vhost.name] = vhost;
        }

        return { port, vhosts };
    }

    loadVirtualHost(dir) {
        /* eslint no-sync: "off" */
        const stat = Fs.statSync(dir);
        if (!stat.isDirectory()) return undefined;

        const config = this.loadVirtualHostConfig(dir);
        const rules = this.loadVirtualHostRules('', dir);

        return this.normalizeVirtualHost(config, rules);
    }

    loadVirtualHostRules(parentPath, dir) {
        const r = {};

        /* eslint no-sync: "off" */
        for (const fileName of Fs.readdirSync(dir)) {
            const full = Path.join(dir, fileName);
            const stat = Fs.statSync(full);
            const path = Path.parse(full);
            const childPath = `${parentPath}/${path.base}`;
            if (stat.isDirectory()) {
                const children = this.loadVirtualHostRules(childPath, full);
                for (let childPath in children) {
                    r[childPath] = children[childPath];
                }
            } else {
                if (QConfig.is(full, _CONFIG_FILE_NAME)) continue;

                const rule = QConfig.load({ dir: path.dir, name: path.name });
                rule.path = parentPath;
                r[childPath] = rule;
            }
        }

        return r;
    }

    loadVirtualHostConfig(dir, dump) {
        const r = QConfig.load({ dir, name: _CONFIG_FILE_NAME }, {}, dump);
        r.name = Path.basename(dir);
        return r;
    }

}


text:
function predicted_values = forecasting_with_VARMAX_horizont(train_set,testset_multivariables,horizon,AR,MA)

%%%%%%%%%%The most important ! The first column is the column which we
%%%%%%%%%%would like to predict !!!!

if size(train_set,2) > size(train_set,1)
    train_set = train_set.';
end

if size(testset_multivariables,2) > size(testset_multivariables,1)
    testset_multivariables = testset_multivariables.';
end
            additional_information = train_set(:,2:end);
            time_series = train_set(:,1);
            Data = [additional_information time_series];
            DataTable = array2table(Data);
            M0 = fitlm(DataTable);
            betaHat0 = M0.Coefficients.Estimate;
            PreSample = additional_information(1:AR,:);
            Sample = additional_information(AR+1:end,:);
            numPreds0 = size(additional_information,2);
            VARSpec = vgxvarx(vgxset('n',numPreds0,'Constant',true,'nAR',AR),Sample,[],PreSample);
            predicted_values = vgxpred(VARSpec,horizon,[],additional_information);
            ForecastX =zeros(horizon,size(predicted_values,2));
            for i=1:1:horizon
            ForecastY(i,:) = [1,predicted_values(i,:)]*betaHat0;
            end
            predicted_values = ForecastY;
end


text:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
                  android:title="Settings">
    <PreferenceCategory android:title="@string/title_history">
        <fr.neamar.kiss.ResetPreference
            android:dialogMessage="Do you really want to reset your history?"
            android:key="reset"
            android:summary="@string/reset_desc"
            android:title="@string/reset_name">
        </fr.neamar.kiss.ResetPreference>
    </PreferenceCategory>
    <PreferenceCategory android:title="@string/title_ui">
        <CheckBoxPreference
            android:defaultValue="false"
            android:key="display-keyboard"
            android:summary="@string/keyboard_desc"
            android:title="@string/keyboard_name">
        </CheckBoxPreference>
    </PreferenceCategory>
    <PreferenceCategory android:title="@string/title_providers">
        <CheckBoxPreference
            android:defaultValue="true"
            android:key="enable-contacts"
            android:summary="@string/contacts_desc"
            android:title="@string/contacts_name">
        </CheckBoxPreference>
        <CheckBoxPreference
            android:defaultValue="true"
            android:key="enable-settings"
            android:summary="@string/settings_desc"
            android:title="@string/settings_name">
        </CheckBoxPreference>
        <CheckBoxPreference
            android:defaultValue="true"
            android:key="enable-toggles"
            android:summary="@string/toggles_desc"
            android:title="@string/toggles_name">
        </CheckBoxPreference>
        <CheckBoxPreference
            android:defaultValue="true"
            android:key="enable-alias"
            android:summary="@string/aliases_desc"
            android:title="@string/aliases_name">
        </CheckBoxPreference>
        <CheckBoxPreference
            android:defaultValue="true"
            android:key="enable-search"
            android:summary="@string/search_desc"
            android:title="@string/search_name">
        </CheckBoxPreference>
        <CheckBoxPreference
            android:defaultValue="true"
            android:key="enable-phone"
            android:summary="@string/phone_desc"
            android:title="@string/phone_name">
        </CheckBoxPreference>
    </PreferenceCategory>

</PreferenceScreen>


text:
#ifndef INCLUDE_MURASAKI_HH_
#define INCLUDE_MURASAKI_HH_

#include <string>
#include "ux/ux.hpp"
#include "fujitsubo.hh"

namespace Genji {

class Murasaki {
public:
	void Open();
	void Convert(const char *kana, std::string &ret);
	void Close();

private:
	ux::Map<GNJ_MAPVAL> *gnjYomiMap;
	ux::Trie *gnjWordTrie;
};

} // namespace Genji

#endif /* INCLUDE_MURASAKI_HH_ */


text:
/**
 * @file color-output.js
 * @description 彩色输出
 */
import chalk from 'chalk';
import { vsprintf } from 'sprintf-js';

function formatStr(format, argv) {
  const s = vsprintf(format, argv);
  return s;
}

function printCrit(format, ...args) {
  console.log(chalk.bgBlue(formatStr(format, args)));
}

function printWarn(format, ...args) {
  console.warn(chalk.red(formatStr(format, args)));
}

function printError(format, ...args) {
  const s = chalk.bgRed(chalk.bold(formatStr(format, args)));
  console.error(s);
}

function printInfo(format, ...args) {
  console.log(formatStr(format, args));
}

function printDebug(format, ...args) {
  console.log(chalk.cyan(formatStr(format, args)));
}

const ColorOut = {
  Red : chalk.red,
  Green: chalk.green,
  Blue: chalk.blue,
  Yellow: chalk.yellow,

  BgRed: chalk.BgRed,
  BgGreen: chalk.bgGreen,
  BgBlue: chalk.bgBlue,
  BgYellow: chalk.bgYellow,

  printCrit,
  printWarn,
  printError,
  printInfo,
  printDebug,

  R : chalk.red,
  G: chalk.green,
  B: chalk.blue,
  Y: chalk.yellow,

  BR: chalk.bgRed,
  BG: chalk.bgGreen,
  BB: chalk.bgBlue,
  BY: chalk.bgYellow,

  logCrit: printCrit,
  logWarn: printWarn,
  logError: printError,
  logInfo: printInfo,
  logDebug: printDebug
};

// export default ColorOut;
module.exports = ColorOut;


text:
<% content_for :class, 'customize' %>

Customize your blog

Ecrire generated a vanilla template for your blog. Everything you see in the folder is for you to modify. As you'll see below, there's already a lot that Ecrire comes with to help you make your blog yours.

Many of the features that are displayed here come directly from Ruby on Rails. This is because Ecrire is built on top of it. That means that if you are already a user of Rails, you know almost everything there is to know about customizing your blog.

Views

Views are where the HTML is built. It is built arount the concept of layout, views and partials. The three elements are nested together to create the HTML that will be sent to the browser — like this page.

The layout

The layout is where you put everything that is reused on every page. The layout is where you set the document type, the <head> element and everything else that you want to have on every page.

<%= Rails.root %>/views/layouts/application.html.erb<%= render('static/customize/layout').to_str %>

One thing you must have in your layout is the <%= yield %> call. This call will inject the view into the layout. If you want to learn more about the layout, Ruby on rails has a great guide that explains the layout more thoroughly.

Views

The post views is where you can customize your HTML dependant of the URL access. Initially, there's two views configured: posts/index.html.erb and posts/show.html.erb

This view is the home page of your blog. If you want to list your post entries, you can do it by adding this code snippet to your view:

<%= Rails.root %>/views/posts/index.html.erb<%= render('static/customize/index').to_str %>

And then add more HTML through a the partial.

<%= Rails.root %>/views/posts/_post.html.erb<%= render('static/customize/post').to_str %>

Helpers

Helpers are modules you can create to define methods that can be used for different purposes.

<%= Rails.root %>/helpers/your_helper.rb<%= render('static/customize/helper').to_str %>

It is automatically available in your views.

<%= Rails.root %>/helpers/your_helper.rb<%= render('static/customize/helper_used').to_str %>

Assets

The assets are the CSS, JS and any images you would like to show on your blog that aren't a part of a blog post. Ecrire — via Rails — provides a few mechanism to help you build customize your theme.

Everything that is described here can be found in use within your default theme. Just browse the code to see an example of what is documented here.

Stylesheets

Stylesheets can either be pure CSS or SASS. Rails will use the SASS preprocessor if the file ends with .scss.

You will notice a file name base.css.scss with a few @import rules. These rules are necessary if you want to include other files besides the required base.css. Since it supports wildcard, you don't need to specify every file in your folder.

You can also add libraries that are available as gem. By default, Ecrire comes with Bourbon, which is imported by default. That means you can have access to all the bourbon mixins from any stylesheet.

Javascripts

Javascripts can either be pure Javascript or Coffeescript.

If you choose to use Coffeescript, you only need to append .coffee to your file to enable the pre-compiler. Similar to your stylesheets, javascript has an import rule. While the @import rule is specified within the CSS Standard, ECMAScript doesn't have such a thing.

Sprockets uses a directive through commenting the top of the file. It uses a similar syntax it shouldn't be too hard to make modification. Also, there's an example from within this theme.

<%= Rails.root %>/assets/javascripts/base.js.coffee<%= render('static/customize/javascript').to_str %>

Note that if you want to use vanilla javascript, you will need to use the commenting syntax for javascript (//=).

Images

Images can be any format that are supported by the browser. However, you need to use a helper when you use images that you put in the assets/images folder.

<%= Rails.root %>/assets/images/header.png<%= render('static/customize/image').to_str %>


text:
import 'vs/css!./hover';
import * as nls from 'vs/nls';
import { IKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import { KeyChord, KeyCode, KeyMod } from 'vs/base/common/keyCodes';
import { IDisposable, DisposableStore, MutableDisposable } from 'vs/base/common/lifecycle';
import { IEmptyContentData } from 'vs/editor/browser/controller/mouseTarget';
import { ICodeEditor, IEditorMouseEvent, MouseTargetType } from 'vs/editor/browser/editorBrowser';
import { EditorAction, ServicesAccessor, registerEditorAction, registerEditorContribution } from 'vs/editor/browser/editorExtensions';
import { ConfigurationChangedEvent, EditorOption } from 'vs/editor/common/config/editorOptions';
import { Range } from 'vs/editor/common/core/range';
import { IEditorContribution, IScrollEvent } from 'vs/editor/common/editorCommon';
import { EditorContextKeys } from 'vs/editor/common/editorContextKeys';
import { IModeService } from 'vs/editor/common/services/modeService';
import { HoverStartMode } from 'vs/editor/contrib/hover/hoverOperation';
import { ModesContentHoverWidget } from 'vs/editor/contrib/hover/modesContentHover';
import { ModesGlyphHoverWidget } from 'vs/editor/contrib/hover/modesGlyphHover';
import { KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry';
import { IOpenerService } from 'vs/platform/opener/common/opener';
import { editorHoverBackground, editorHoverBorder, editorHoverHighlight, textCodeBlockBackground, textLinkForeground, editorHoverStatusBarBackground, editorHoverForeground } from 'vs/platform/theme/common/colorRegistry';
import { IThemeService, registerThemingParticipant } from 'vs/platform/theme/common/themeService';
import { IMarkerDecorationsService } from 'vs/editor/common/services/markersDecorationService';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { AccessibilitySupport } from 'vs/platform/accessibility/common/accessibility';
import { GotoDefinitionAtPositionEditorContribution } from 'vs/editor/contrib/gotoSymbol/link/goToDefinitionAtPosition';

export class ModesHoverController implements IEditorContribution {

	public static readonly ID = 'editor.contrib.hover';

	private readonly _toUnhook = new DisposableStore();
	private readonly _didChangeConfigurationHandler: IDisposable;

	private readonly _contentWidget = new MutableDisposable<ModesContentHoverWidget>();
	private readonly _glyphWidget = new MutableDisposable<ModesGlyphHoverWidget>();

	get contentWidget(): ModesContentHoverWidget {
		if (!this._contentWidget.value) {
			this._createHoverWidgets();
		}
		return this._contentWidget.value!;
	}

	get glyphWidget(): ModesGlyphHoverWidget {
		if (!this._glyphWidget.value) {
			this._createHoverWidgets();
		}
		return this._glyphWidget.value!;
	}

	private _isMouseDown: boolean;
	private _hoverClicked: boolean;
	private _isHoverEnabled!: boolean;
	private _isHoverSticky!: boolean;

	static get(editor: ICodeEditor): ModesHoverController {
		return editor.getContribution<ModesHoverController>(ModesHoverController.ID);
	}

	constructor(private readonly _editor: ICodeEditor,
		@IOpenerService private readonly _openerService: IOpenerService,
		@IModeService private readonly _modeService: IModeService,
		@IMarkerDecorationsService private readonly _markerDecorationsService: IMarkerDecorationsService,
		@IKeybindingService private readonly _keybindingService: IKeybindingService,
		@IThemeService private readonly _themeService: IThemeService
	) {
		this._isMouseDown = false;
		this._hoverClicked = false;

		this._hookEvents();

		this._didChangeConfigurationHandler = this._editor.onDidChangeConfiguration((e: ConfigurationChangedEvent) => {
			if (e.hasChanged(EditorOption.hover)) {
				this._hideWidgets();
				this._unhookEvents();
				this._hookEvents();
			}
		});
	}

	private _hookEvents(): void {
		const hideWidgetsEventHandler = () => this._hideWidgets();

		const hoverOpts = this._editor.getOption(EditorOption.hover);
		this._isHoverEnabled = hoverOpts.enabled;
		this._isHoverSticky = hoverOpts.sticky;
		if (this._isHoverEnabled) {
			this._toUnhook.add(this._editor.onMouseDown((e: IEditorMouseEvent) => this._onEditorMouseDown(e)));
			this._toUnhook.add(this._editor.onMouseUp((e: IEditorMouseEvent) => this._onEditorMouseUp(e)));
			this._toUnhook.add(this._editor.onMouseMove((e: IEditorMouseEvent) => this._onEditorMouseMove(e)));
			this._toUnhook.add(this._editor.onKeyDown((e: IKeyboardEvent) => this._onKeyDown(e)));
			this._toUnhook.add(this._editor.onDidChangeModelDecorations(() => this._onModelDecorationsChanged()));
		} else {
			this._toUnhook.add(this._editor.onMouseMove(hideWidgetsEventHandler));
		}

		this._toUnhook.add(this._editor.onMouseLeave(hideWidgetsEventHandler));
		this._toUnhook.add(this._editor.onDidChangeModel(hideWidgetsEventHandler));
		this._toUnhook.add(this._editor.onDidScrollChange((e: IScrollEvent) => this._onEditorScrollChanged(e)));
	}

	private _unhookEvents(): void {
		this._toUnhook.clear();
	}

	private _onModelDecorationsChanged(): void {
		this.contentWidget.onModelDecorationsChanged();
		this.glyphWidget.onModelDecorationsChanged();
	}

	private _onEditorScrollChanged(e: IScrollEvent): void {
		if (e.scrollTopChanged || e.scrollLeftChanged) {
			this._hideWidgets();
		}
	}

	private _onEditorMouseDown(mouseEvent: IEditorMouseEvent): void {
		this._isMouseDown = true;

		const targetType = mouseEvent.target.type;

		if (targetType === MouseTargetType.CONTENT_WIDGET && mouseEvent.target.detail === ModesContentHoverWidget.ID) {
			this._hoverClicked = true;
			// mouse down on top of content hover widget
			return;
		}

		if (targetType === MouseTargetType.OVERLAY_WIDGET && mouseEvent.target.detail === ModesGlyphHoverWidget.ID) {
			// mouse down on top of overlay hover widget
			return;
		}

		if (targetType !== MouseTargetType.OVERLAY_WIDGET && mouseEvent.target.detail !== ModesGlyphHoverWidget.ID) {
			this._hoverClicked = false;
		}

		this._hideWidgets();
	}

	private _onEditorMouseUp(mouseEvent: IEditorMouseEvent): void {
		this._isMouseDown = false;
	}

	private _onEditorMouseMove(mouseEvent: IEditorMouseEvent): void {
		let targetType = mouseEvent.target.type;

		if (this._isMouseDown && this._hoverClicked && this.contentWidget.isColorPickerVisible()) {
			return;
		}

		if (this._isHoverSticky && targetType === MouseTargetType.CONTENT_WIDGET && mouseEvent.target.detail === ModesContentHoverWidget.ID) {
			// mouse moved on top of content hover widget
			return;
		}

		if (this._isHoverSticky && targetType === MouseTargetType.OVERLAY_WIDGET && mouseEvent.target.detail === ModesGlyphHoverWidget.ID) {
			// mouse moved on top of overlay hover widget
			return;
		}

		if (targetType === MouseTargetType.CONTENT_EMPTY) {
			const epsilon = this._editor.getOption(EditorOption.fontInfo).typicalHalfwidthCharacterWidth / 2;
			const data = <IEmptyContentData>mouseEvent.target.detail;
			if (data && !data.isAfterLines && typeof data.horizontalDistanceToText === 'number' && data.horizontalDistanceToText < epsilon) {
				// Let hover kick in even when the mouse is technically in the empty area after a line, given the distance is small enough
				targetType = MouseTargetType.CONTENT_TEXT;
			}
		}

		if (targetType === MouseTargetType.CONTENT_TEXT) {
			this.glyphWidget.hide();

			if (this._isHoverEnabled && mouseEvent.target.range) {
				this.contentWidget.startShowingAt(mouseEvent.target.range, HoverStartMode.Delayed, false);
			}
		} else if (targetType === MouseTargetType.GUTTER_GLYPH_MARGIN) {
			this.contentWidget.hide();

			if (this._isHoverEnabled && mouseEvent.target.position) {
				this.glyphWidget.startShowingAt(mouseEvent.target.position.lineNumber);
			}
		} else {
			this._hideWidgets();
		}
	}

	private _onKeyDown(e: IKeyboardEvent): void {
		if (e.keyCode !== KeyCode.Ctrl && e.keyCode !== KeyCode.Alt && e.keyCode !== KeyCode.Meta && e.keyCode !== KeyCode.Shift) {
			// Do not hide hover when a modifier key is pressed
			this._hideWidgets();
		}
	}

	private _hideWidgets(): void {
		if (!this._glyphWidget.value || !this._contentWidget.value || (this._isMouseDown && this._hoverClicked && this._contentWidget.value.isColorPickerVisible())) {
			return;
		}

		this._glyphWidget.value.hide();
		this._contentWidget.value.hide();
	}

	private _createHoverWidgets() {
		this._contentWidget.value = new ModesContentHoverWidget(this._editor, this._markerDecorationsService, this._themeService, this._keybindingService, this._modeService, this._openerService);
		this._glyphWidget.value = new ModesGlyphHoverWidget(this._editor, this._modeService, this._openerService);
	}

	public showContentHover(range: Range, mode: HoverStartMode, focus: boolean): void {
		this.contentWidget.startShowingAt(range, mode, focus);
	}

	public dispose(): void {
		this._unhookEvents();
		this._toUnhook.dispose();
		this._didChangeConfigurationHandler.dispose();
		this._glyphWidget.dispose();
		this._contentWidget.dispose();
	}
}

class ShowHoverAction extends EditorAction {

	constructor() {
		super({
			id: 'editor.action.showHover',
			label: nls.localize({
				key: 'showHover',
				comment: [
					'Label for action that will trigger the showing of a hover in the editor.',
					'This allows for users to show the hover without using the mouse.'
				]
			}, "Show Hover"),
			alias: 'Show Hover',
			precondition: undefined,
			kbOpts: {
				kbExpr: EditorContextKeys.editorTextFocus,
				primary: KeyChord(KeyMod.CtrlCmd | KeyCode.KEY_K, KeyMod.CtrlCmd | KeyCode.KEY_I),
				weight: KeybindingWeight.EditorContrib
			}
		});
	}

	public run(accessor: ServicesAccessor, editor: ICodeEditor): void {
		if (!editor.hasModel()) {
			return;
		}
		let controller = ModesHoverController.get(editor);
		if (!controller) {
			return;
		}
		const position = editor.getPosition();
		const range = new Range(position.lineNumber, position.column, position.lineNumber, position.column);
		const focus = editor.getOption(EditorOption.accessibilitySupport) === AccessibilitySupport.Enabled;
		controller.showContentHover(range, HoverStartMode.Immediate, focus);
	}
}

class ShowDefinitionPreviewHoverAction extends EditorAction {

	constructor() {
		super({
			id: 'editor.action.showDefinitionPreviewHover',
			label: nls.localize({
				key: 'showDefinitionPreviewHover',
				comment: [
					'Label for action that will trigger the showing of definition preview hover in the editor.',
					'This allows for users to show the definition preview hover without using the mouse.'
				]
			}, "Show Definition Preview Hover"),
			alias: 'Show Definition Preview Hover',
			precondition: undefined
		});
	}

	public run(accessor: ServicesAccessor, editor: ICodeEditor): void {
		let controller = ModesHoverController.get(editor);
		if (!controller) {
			return;
		}
		const position = editor.getPosition();

		if (!position) {
			return;
		}

		const range = new Range(position.lineNumber, position.column, position.lineNumber, position.column);
		const goto = GotoDefinitionAtPositionEditorContribution.get(editor);
		const promise = goto.startFindDefinitionFromCursor(position);
		if (promise) {
			promise.then(() => {
				controller.showContentHover(range, HoverStartMode.Immediate, true);
			});
		} else {
			controller.showContentHover(range, HoverStartMode.Immediate, true);
		}
	}
}

registerEditorContribution(ModesHoverController.ID, ModesHoverController);
registerEditorAction(ShowHoverAction);
registerEditorAction(ShowDefinitionPreviewHoverAction);

// theming
registerThemingParticipant((theme, collector) => {
	const editorHoverHighlightColor = theme.getColor(editorHoverHighlight);
	if (editorHoverHighlightColor) {
		collector.addRule(`.monaco-editor .hoverHighlight { background-color: ${editorHoverHighlightColor}; }`);
	}
	const hoverBackground = theme.getColor(editorHoverBackground);
	if (hoverBackground) {
		collector.addRule(`.monaco-editor .monaco-editor-hover { background-color: ${hoverBackground}; }`);
	}
	const hoverBorder = theme.getColor(editorHoverBorder);
	if (hoverBorder) {
		collector.addRule(`.monaco-editor .monaco-editor-hover { border: 1px solid ${hoverBorder}; }`);
		collector.addRule(`.monaco-editor .monaco-editor-hover .hover-row:not(:first-child):not(:empty) { border-top: 1px solid ${hoverBorder.transparent(0.5)}; }`);
		collector.addRule(`.monaco-editor .monaco-editor-hover hr { border-top: 1px solid ${hoverBorder.transparent(0.5)}; }`);
		collector.addRule(`.monaco-editor .monaco-editor-hover hr { border-bottom: 0px solid ${hoverBorder.transparent(0.5)}; }`);
	}
	const link = theme.getColor(textLinkForeground);
	if (link) {
		collector.addRule(`.monaco-editor .monaco-editor-hover a { color: ${link}; }`);
	}
	const hoverForeground = theme.getColor(editorHoverForeground);
	if (hoverForeground) {
		collector.addRule(`.monaco-editor .monaco-editor-hover { color: ${hoverForeground}; }`);
	}
	const actionsBackground = theme.getColor(editorHoverStatusBarBackground);
	if (actionsBackground) {
		collector.addRule(`.monaco-editor .monaco-editor-hover .hover-row .actions { background-color: ${actionsBackground}; }`);
	}
	const codeBackground = theme.getColor(textCodeBlockBackground);
	if (codeBackground) {
		collector.addRule(`.monaco-editor .monaco-editor-hover code { background-color: ${codeBackground}; }`);
	}
});


text:
<?xml version="1.0" encoding="UTF-8"?>
<image-types>
	<image-type>
        <name>Verizon Cloud Image</name>
        <description>Verizon Cloud Image</description>
		<property-definitions>
            <property-definition>
                <name>OS Image</name>
                <description>OS Image</description>
                <required>true</required>
                <type>STRING</type>
                <default-string-value></default-string-value>
                <string-max-length>80</string-max-length>
                <allowed-string-values>pfSense 2.1.2 x64,Big IP F5 11.5.2,CentOS 7 x64,Ubuntu 12.04 LTS x64,Ubuntu 14.04 LTS x64,FreeBSD 10.0 x64,Windows Server 2008 Standard SQL 2008 R2 Web 64-Bit 40GB,Windows Server 2008 Standard 64-Bit 40GB,Windows Server 2008 Enterprise 64-Bit 40GB,Windows Server 2008 Standard SQL 2008 R2 Standard 64-Bit 40GB,Windows Server 2012 SQL 2012 Web 64-Bit 50GB,Windows Server 2012 SQL 2012 Standard 64-Bit 50GB,Windows Server 2012 64-Bit 50GB,Juniper Firefly 12.1x47,Debian 7 (Wheezy) x86_64,centos 6.6 x86_64,CentOS 5.11 x64,Red Hat Enterprise Linux 5.11 x86_64,Red Hat Enterprise Linux 6.6 x86_64,CentOS 6.6 x64 with Docker</allowed-string-values>
                <default-file-value></default-file-value>
            </property-definition>
            <property-definition>
                <name>Account</name>
                <description>Verizon account ID or Number</description>
                <required>true</required>
                <type>STRING</type>
                <default-string-value></default-string-value>
                <string-max-length>80</string-max-length>
                <allowed-string-values></allowed-string-values>
                <default-file-value></default-file-value>
            </property-definition>
            <property-definition>
                <name>Cloudspace</name>
                <description>Verizon cloudspace name</description>
                <required>true</required>
                <type>STRING</type>
                <default-string-value></default-string-value>
                <string-max-length>80</string-max-length>
                <allowed-string-values></allowed-string-values>
                <default-file-value></default-file-value>
            </property-definition>
		</property-definitions>
		<supported-compute-center-types>
			<compute-center-type>Verizon Cloud</compute-center-type>
		</supported-compute-center-types>
	</image-type>
</image-types>


text:
function podPress_makeAjaxRequest(url, podPressHTML5sec, podPressBackendURL) {
	if ( typeof podPressBackendURL == 'string' && podPressBackendURL != '' && typeof podPressHTML5sec == 'string' && podPressHTML5sec != '' ) {
		podpress_http_request = false;
		if (window.XMLHttpRequest) { // Mozilla, Safari,...
			podpress_http_request = new XMLHttpRequest();
			if (podpress_http_request.overrideMimeType) {
				podpress_http_request.overrideMimeType('text/html');
			}
		} else if (window.ActiveXObject) { // IE
			try {
				podpress_http_request = new ActiveXObject("Msxml2.XMLHTTP");
			} catch (e) {
				try {
					podpress_http_request = new ActiveXObject("Microsoft.XMLHTTP");
				} catch (e) {}
			}
		}
		if (!podpress_http_request) {
			//~ alert('It is not possible to create an XMLHTTP instance.');
			return false;
		}
		podpress_http_request.open('POST', podPressBackendURL + 'podpress_backend.php', true);
		podpress_http_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		podpress_http_request.send( 'action=getrealurl&url='+encodeURIComponent(url)+'&_ajax_nonce=' + podPressHTML5sec );
		//~ podpress_http_request.onreadystatechange = function() { podPress_AjaxResponse(); }
	}
}

function podPress_AjaxResponse() {
	switch (podpress_http_request.readyState) {
		case 0 : // UNINITIALIZED
		case 1 : // LOADING
		case 2 : // LOADED
		case 3 : // INTERACTIVE
			break;
		case 4 : // COMPLETED
			if (podpress_http_request.status == 200) {
				alert('podpress_http_request.status: \n' + podpress_http_request.status + '\n data:\n ' + podpress_http_request.responseText);
			} else {
				alert('There was a problem with the request (Probably no data saved). podpress_http_request.status: \n' + podpress_http_request.status + '\n Error message:\n ' + podpress_http_request.responseText);
			}
			break;
		default : ; // fehlerhafter Status
	}
}


text:
using System;
using System.Numerics;
using System.Runtime.CompilerServices;

using Microsoft.Scripting.Runtime;

#pragma warning disable 675

namespace IronPython.Runtime.Operations {

    #region Generated FloatOps

    // *** BEGIN GENERATED CODE ***
    // generated by function: gen_float from: generate_alltypes.py

    public static partial class SingleOps {

        #region Unary Operations

        [SpecialName]
        public static Single Plus(Single x) => x;

        [SpecialName]
        public static Single Negate(Single x) => (Single)(-(x));

        [SpecialName]
        public static Single Abs(Single x) => (Single)(Math.Abs(x));

        public static bool __bool__(Single x) => (x != 0);

        public static object __trunc__(Single x) {
            if (x >= int.MaxValue || x <= int.MinValue) {
                return (BigInteger)x;
            } else {
                return (int)x;
            }
        }

        #endregion

        #region Binary Operations - Arithmetic

        [SpecialName]
        public static Single Add(Single x, Single y) {
            return x + y;
        }

        [SpecialName]
        public static Single Subtract(Single x, Single y) {
            return x - y;
        }

        [SpecialName]
        public static Single Multiply(Single x, Single y) {
            return x * y;
        }

        [SpecialName]
        public static Single TrueDivide(Single x, Single y) {
            if (y == 0) throw PythonOps.ZeroDivisionError();
            return x / y;
        }

        [SpecialName]
        public static Single FloorDivide(Single x, Single y) {
            if (y == 0) throw PythonOps.ZeroDivisionError();
            return (Single)Math.Floor(x / y);
        }

        #endregion

        #region Conversion operators

        [SpecialName, ExplicitConversionMethod]
        public static SByte ConvertToSByte(Single x) {
            if (SByte.MinValue <= x && x <= SByte.MaxValue) {
                return (SByte)x;
            }
            throw Converter.CannotConvertOverflow("SByte", x);
        }

        [SpecialName, ExplicitConversionMethod]
        public static Byte ConvertToByte(Single x) {
            if (Byte.MinValue <= x && x <= Byte.MaxValue) {
                return (Byte)x;
            }
            throw Converter.CannotConvertOverflow("Byte", x);
        }

        [SpecialName, ExplicitConversionMethod]
        public static Int16 ConvertToInt16(Single x) {
            if (Int16.MinValue <= x && x <= Int16.MaxValue) {
                return (Int16)x;
            }
            throw Converter.CannotConvertOverflow("Int16", x);
        }

        [SpecialName, ExplicitConversionMethod]
        public static UInt16 ConvertToUInt16(Single x) {
            if (UInt16.MinValue <= x && x <= UInt16.MaxValue) {
                return (UInt16)x;
            }
            throw Converter.CannotConvertOverflow("UInt16", x);
        }

        [SpecialName, ExplicitConversionMethod]
        public static Int32 ConvertToInt32(Single x) {
            if (Int32.MinValue <= x && x <= Int32.MaxValue) {
                return (Int32)x;
            }
            throw Converter.CannotConvertOverflow("Int32", x);
        }

        [SpecialName, ExplicitConversionMethod]
        public static UInt32 ConvertToUInt32(Single x) {
            if (UInt32.MinValue <= x && x <= UInt32.MaxValue) {
                return (UInt32)x;
            }
            throw Converter.CannotConvertOverflow("UInt32", x);
        }

        [SpecialName, ExplicitConversionMethod]
        public static Int64 ConvertToInt64(Single x) {
            if (Int64.MinValue <= x && x <= Int64.MaxValue) {
                return (Int64)x;
            }
            throw Converter.CannotConvertOverflow("Int64", x);
        }

        [SpecialName, ExplicitConversionMethod]
        public static UInt64 ConvertToUInt64(Single x) {
            if (UInt64.MinValue <= x && x <= UInt64.MaxValue) {
                return (UInt64)x;
            }
            throw Converter.CannotConvertOverflow("UInt64", x);
        }

        [SpecialName, ImplicitConversionMethod]
        public static Double ConvertToDouble(Single x) => (Double)x;

        #endregion

        #region Public API - Numerics

        [PropertyMethod, SpecialName]
        public static Single Getreal(Single x) => x;

        [PropertyMethod, SpecialName]
        public static Single Getimag(Single x) => (Single)0;

        public static Single conjugate(Single x) => x;

        #endregion
    }

    public static partial class DoubleOps {

        #region Unary Operations

        [SpecialName]
        public static Double Plus(Double x) => x;

        [SpecialName]
        public static Double Negate(Double x) => (Double)(-(x));

        [SpecialName]
        public static Double Abs(Double x) => (Double)(Math.Abs(x));

        public static bool __bool__(Double x) => (x != 0);

        public static object __trunc__(Double x) {
            if (x >= int.MaxValue || x <= int.MinValue) {
                return (BigInteger)x;
            } else {
                return (int)x;
            }
        }

        #endregion

        #region Binary Operations - Arithmetic

        [SpecialName]
        public static Double Add(Double x, Double y) {
            return x + y;
        }

        [SpecialName]
        public static Double Subtract(Double x, Double y) {
            return x - y;
        }

        [SpecialName]
        public static Double Multiply(Double x, Double y) {
            return x * y;
        }

        [SpecialName]
        public static Double TrueDivide(Double x, Double y) {
            if (y == 0) throw PythonOps.ZeroDivisionError();
            return x / y;
        }

        [SpecialName]
        public static Double FloorDivide(Double x, Double y) {
            if (y == 0) throw PythonOps.ZeroDivisionError();
            return (Double)Math.Floor(x / y);
        }

        #endregion

        #region Conversion operators

        [SpecialName, ExplicitConversionMethod]
        public static SByte ConvertToSByte(Double x) {
            if (SByte.MinValue <= x && x <= SByte.MaxValue) {
                return (SByte)x;
            }
            throw Converter.CannotConvertOverflow("SByte", x);
        }

        [SpecialName, ExplicitConversionMethod]
        public static Byte ConvertToByte(Double x) {
            if (Byte.MinValue <= x && x <= Byte.MaxValue) {
                return (Byte)x;
            }
            throw Converter.CannotConvertOverflow("Byte", x);
        }

        [SpecialName, ExplicitConversionMethod]
        public static Int16 ConvertToInt16(Double x) {
            if (Int16.MinValue <= x && x <= Int16.MaxValue) {
                return (Int16)x;
            }
            throw Converter.CannotConvertOverflow("Int16", x);
        }

        [SpecialName, ExplicitConversionMethod]
        public static UInt16 ConvertToUInt16(Double x) {
            if (UInt16.MinValue <= x && x <= UInt16.MaxValue) {
                return (UInt16)x;
            }
            throw Converter.CannotConvertOverflow("UInt16", x);
        }

        [SpecialName, ExplicitConversionMethod]
        public static Int32 ConvertToInt32(Double x) {
            if (Int32.MinValue <= x && x <= Int32.MaxValue) {
                return (Int32)x;
            }
            throw Converter.CannotConvertOverflow("Int32", x);
        }

        [SpecialName, ExplicitConversionMethod]
        public static UInt32 ConvertToUInt32(Double x) {
            if (UInt32.MinValue <= x && x <= UInt32.MaxValue) {
                return (UInt32)x;
            }
            throw Converter.CannotConvertOverflow("UInt32", x);
        }

        [SpecialName, ExplicitConversionMethod]
        public static Int64 ConvertToInt64(Double x) {
            if (Int64.MinValue <= x && x <= Int64.MaxValue) {
                return (Int64)x;
            }
            throw Converter.CannotConvertOverflow("Int64", x);
        }

        [SpecialName, ExplicitConversionMethod]
        public static UInt64 ConvertToUInt64(Double x) {
            if (UInt64.MinValue <= x && x <= UInt64.MaxValue) {
                return (UInt64)x;
            }
            throw Converter.CannotConvertOverflow("UInt64", x);
        }

        [SpecialName, ImplicitConversionMethod]
        public static Single ConvertToSingle(Double x) => (Single)x;

        #endregion

        #region Public API - Numerics

        [PropertyMethod, SpecialName]
        public static Double Getreal(Double x) => x;

        [PropertyMethod, SpecialName]
        public static Double Getimag(Double x) => (Double)0;

        public static Double conjugate(Double x) => x;

        #endregion
    }

    // *** END GENERATED CODE ***

    #endregion
}


text:
package org.fcrepo.server.security.xacml.test;

import java.util.HashMap;
import java.util.Map;

import org.fcrepo.server.security.xacml.util.RelationshipResolverImpl;

public class TestRelationshipResolverImpl {

    private RelationshipResolverImpl rels = null;

    /**
     * @param args
     */
    public static void main(String[] args) {
        TestRelationshipResolverImpl app = null;
        try {
            app = new TestRelationshipResolverImpl();
            app.test01();
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
    }

    public TestRelationshipResolverImpl()
            throws Exception {
        Map<String, String> options = new HashMap<String, String>();
        options.put("url", "http://localhost:8080/fedora/melcoerisearch");
        options.put("username", "");
        options.put("password", "");
        rels = new RelationshipResolverImpl(options);
    }

    public void test01() throws Exception {
        String result = rels.buildRESTParentHierarchy("changeme:8848");
        System.out.println(result);
    }
}


text:
package org.apache.hive.beeline;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

import jline.console.completer.AggregateCompleter;
import jline.console.completer.Completer;
import jline.console.completer.NullCompleter;
import jline.console.completer.StringsCompleter;

class BeeLineCommandCompleter extends AggregateCompleter {

  public BeeLineCommandCompleter(List<Completer> completers) {
    super(completers);
  }

  public static List<Completer> getCompleters(BeeLine beeLine){
    List<Completer> completers = new LinkedList<Completer>();

    for (int i = 0; i < beeLine.commandHandlers.length; i++) {
      String[] cmds = beeLine.commandHandlers[i].getNames();
      for (int j = 0; cmds != null && j < cmds.length; j++) {
        List<Completer> compl = new LinkedList<Completer>();
        compl.add(new StringsCompleter(BeeLine.COMMAND_PREFIX + cmds[j]));
        compl.addAll(Arrays.asList(beeLine.commandHandlers[i].getParameterCompleters()));
        compl.add(new NullCompleter()); // last param no complete
        completers.add(new AggregateCompleter(compl.toArray(new Completer[0])));
      }
    }
    return completers;
  }
}


text:
package com.google.arcs;

import com.intellij.openapi.fileTypes.*;
import org.jetbrains.annotations.NotNull;

public class ArcsFileTypeFactory extends FileTypeFactory {

  private static final FileNameMatcher EXTENSION_MATCHER = new ExtensionFileNameMatcher("arcs");

  @Override
  public void createFileTypes(@NotNull FileTypeConsumer fileTypeConsumer) {
    fileTypeConsumer.consume(ArcsFileType.INSTANCE, EXTENSION_MATCHER);
  }
}


text:
package edu.wheaton.simulator.gui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JTextField;

import edu.wheaton.simulator.gui.screen.Screen;
import edu.wheaton.simulator.gui.screen.ViewSimScreen;

public class ConwayFinishListener implements ActionListener {

	private JTextField name;
	private JTextField width;
	private JTextField height;
	private SimulatorFacade gm;

	public ConwayFinishListener(JTextField name, JTextField width, JTextField height,
			SimulatorFacade gm){
		this.name = name;
		this.width = width;
		this.height = height;
		this.gm = gm;
	}
	@Override
	public void actionPerformed(ActionEvent e) {
		try {
			int heightInt = getHeight();
			int widthInt = getWidth();
			gm.load(name.getText(),widthInt, heightInt);
			gm.updateGuiManager(getName(), widthInt, heightInt);
		} catch(java.lang.NumberFormatException nfe) {
			System.err.println("Invalid input passed to ConwayFinishListener");
		}

		Screen upload = Gui.getScreenManager().getScreen("View Simulation");
		((ViewSimScreen)upload).init();
		gm.initGameOfLife();
		gm.setStepLimit(1000);
		gm.setStarted(false);
		Gui.getScreenManager().load(upload);
	}
	public String getName(){
		return name.getText();
	}
	public int getHeight(){
		return Integer.parseInt(height.getText());
	}
	public int getWidth(){
		return Integer.parseInt(width.getText());
	}
}


text:
package ca.ualberta.cs.c301f12t01.serverStorage;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.apache.http.message.BasicNameValuePair;

import ca.ualberta.cs.c301f12t01.common.MediaType;
import ca.ualberta.cs.c301f12t01.common.PhotoResponse;
import ca.ualberta.cs.c301f12t01.common.Report;
import ca.ualberta.cs.c301f12t01.common.Response;
import ca.ualberta.cs.c301f12t01.common.Sharing;
import ca.ualberta.cs.c301f12t01.common.Task;
import ca.ualberta.cs.c301f12t01.common.TextResponse;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;

/**
 *
 * @author home
 *
 */
public class ReportServerRetrieval {

	public static class ResponseDeserializer implements JsonDeserializer<Response> {

		/* (non-Javadoc)
		 * @see com.google.gson.JsonDeserializer#deserialize(com.google.gson.JsonElement, java.lang.reflect.Type, com.google.gson.JsonDeserializationContext)
		 */
		public Response deserialize(JsonElement json, Type type,
				JsonDeserializationContext context) throws JsonParseException {
			JsonObject responseObject = json.getAsJsonObject();

			MediaType media = MediaType.valueOf(responseObject.get("mediaType").getAsString());

			switch (media) {
			case TEXT:
				return new TextResponse(responseObject.get("text").getAsString());
			case PHOTO:
				String imageData = responseObject.get("photoData64").getAsString();
				String imageType = responseObject.get("type").getAsString();
				return new PhotoResponse(imageData, imageType);
			case AUDIO:
				System.err.println("CANNOT COPE WITH AUDIO TYPE!");
				assert false;
				return null;
			}

			return null;
		}

	}

	/**
	 *
	 * @return all simple server objects on server
	 */
	public static ReportServerObj[] getAllSO() {
		// first make the call to the server
		List<BasicNameValuePair> nvp = new ArrayList<BasicNameValuePair>();
		nvp.add(new BasicNameValuePair("action", "list"));
		Server server = new Server();
		String jsonString = server.post(nvp);
		// Now convert to an array of server objects
		Gson gson = new Gson();
		ReportServerObj[] allSO = gson.fromJson(jsonString,
				ReportServerObj[].class);
		return allSO;
	}

	/**
	 *
	 * @return all reports on the server
	 */
	public static ArrayList<Report> getAllReports() {
		ReportServerObj[] allSO = getAllSO();
		ArrayList<Report> reports = new ArrayList<Report>();
		// iterate through and grab task
		for (ReportServerObj so : allSO) {
			if (so.getSummary().equals("report")) {
				Report r = getContentFromServer(so.getId());
				reports.add(r);
			}
		}
		return reports;
	}

	/**
	 * @param matchingTask
	 *            Task that reports should belong to
	 * @return all reports on the server that match matchingTask
	 */
	public static ArrayList<Report> getAllReports(Task matchingTask) {
		ReportServerObj[] allSO = getAllSO();
		ArrayList<Report> reports = new ArrayList<Report>();
		// iterate through and grab task
		for (ReportServerObj so : allSO) {
			if (so.getSummary().equals("report")) {
				Report r = getContentFromServer(so.getId());
				if (r.getTaskID().equals(matchingTask.getId())) {
					reports.add(r);
				}
			}
		}
		return reports;
	}

	/**
	 *
	 * @param taskID
	 *            UUID that report's taskID should match
	 * @return ArrayList of reports that match taskID
	 */
	public static ArrayList<Report> getTaskReports(UUID taskID) {
		ArrayList<Report> al = getAllReports();
		ArrayList<Report> task = new ArrayList<Report>();
		for (Report r : al) {
			if (r.getTaskID().equals(taskID)) {
				task.add(r);
			}
		}
		return task;
	}

	/**
	 *
	 * @param matchingTask
	 *            Task that reports should belong to
	 * @return ArrayList of global reports
	 */
	public static ArrayList<Report> getGlobalReports(Task matchingTask) {
		ArrayList<Report> al = getAllReports();
		ArrayList<Report> toReturn = new ArrayList<Report>();
		for (Report r : al) {
			if (r.getSharing().equals(Sharing.GLOBAL)
					&& r.getTaskID().equals(matchingTask.getId())) {
				toReturn.add(r);
			}
		}
		return toReturn;
	}

	/**
	 *
	 * @param matchingTask
	 *            Task that reports should belong to
	 * @return ArrayList of local reports
	 */
	public static ArrayList<Report> getLocalReports(Task matchingTask) {
		ArrayList<Report> al = getAllReports();
		ArrayList<Report> toReturn = new ArrayList<Report>();
		for (Report r : al) {
			if (r.getSharing().equals(Sharing.LOCAL)
					&& r.getTaskID().equals(matchingTask.getId())) {
				toReturn.add(r);
			}
		}
		return toReturn;
	}

	/**
	 * Method works to get reports and tasks
	 *
	 * @param id
	 *            Server ID of the content we want to get
	 * @return content from server
	 */
	public static Report getContentFromServer(String id) {
		// create our nvp
		List<BasicNameValuePair> nvp = new ArrayList<BasicNameValuePair>();
		nvp.add(new BasicNameValuePair("action", "get"));
		nvp.add(new BasicNameValuePair("id", id));
		// post
		Server server = new Server();
		String jsonString = server.post(nvp);

		// convert to SO
		GsonBuilder gsonBuilder = new GsonBuilder();
		gsonBuilder.registerTypeAdapter(Response.class, new ResponseDeserializer());
		Gson gson = gsonBuilder.create();

		ReportServerObj so = gson.fromJson(jsonString, ReportServerObj.class);
		return so.getContent();
	}

}


text:
from coalib.bearlib.abstractions.Linter import linter
from dependency_management.requirements.NpmRequirement import NpmRequirement

@linter(executable='csslint',
        output_format='regex',
        output_regex=r'.+: *(?:line (?P<line>\d+), '
                     r'col (?P<column>\d+), )?(?P<severity>Error|Warning) - '
                     r'(?P<message>.*)')
class CSSLintBear:
    """
    Check code for syntactical or semantical problems that might lead to
    problems or inefficiencies.
    """
    LANGUAGES = {'CSS'}
    REQUIREMENTS = {NpmRequirement('csslint', '1')}
    AUTHORS = {'The coala developers'}
    AUTHORS_EMAILS = {'coala-devel@googlegroups.com'}
    LICENSE = 'AGPL-3.0'
    CAN_DETECT = {'Syntax', 'Code Simplification'}

    @staticmethod
    def create_arguments(filename, file, config_file):
        return '--format=compact', filename