text:
package com.bluecirclesoft.open.jigen.jacksonModeller;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.lang.reflect.WildcardType;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Supplier;

import org.reflections.Reflections;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.bluecirclesoft.open.jigen.ClassOverrideHandler;
import com.bluecirclesoft.open.jigen.model.JAny;
import com.bluecirclesoft.open.jigen.model.JArray;
import com.bluecirclesoft.open.jigen.model.JBoolean;
import com.bluecirclesoft.open.jigen.model.JEnum;
import com.bluecirclesoft.open.jigen.model.JMap;
import com.bluecirclesoft.open.jigen.model.JNumber;
import com.bluecirclesoft.open.jigen.model.JSpecialization;
import com.bluecirclesoft.open.jigen.model.JString;
import com.bluecirclesoft.open.jigen.model.JType;
import com.bluecirclesoft.open.jigen.model.JTypeVariable;
import com.bluecirclesoft.open.jigen.model.JVoid;
import com.bluecirclesoft.open.jigen.model.JWildcard;
import com.bluecirclesoft.open.jigen.model.Model;
import com.bluecirclesoft.open.jigen.model.PropertyEnumerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonAnyFormatVisitor;
import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonArrayFormatVisitor;
import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonBooleanFormatVisitor;
import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonFormatTypes;
import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonFormatVisitable;
import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonFormatVisitorWrapper;
import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonIntegerFormatVisitor;
import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonMapFormatVisitor;
import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonNullFormatVisitor;
import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonNumberFormatVisitor;
import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonObjectFormatVisitor;
import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonStringFormatVisitor;
import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonValueFormat;

/**
 *
The JacksonTypeModeller coordinates the reading of a set of Java types, producing TypeScript types from them, and collecting the
 * resulting TS types into a Model.

 *
This class uses a breadth-first search to find referenced types. When a type is processed, all the types it references are placed on a
 * queue, and the process is repeated until the queue is empty.

 *
To ease the eventual reading of the model, I wanted to make sure that if a type in the TS model references another type, that it's
 * a direct reference, to avoid having to go to a lookup table or something like that.  This is necessary, in particular, for circular
 * references - one type clearly can't have a reference to another type that hasn't been digested yet. So to solve this, as types are
 * read, the modeller stores 'fixups' to join the types properly later. This creates two steps:

 *

 *
All types are read, but references to other types are stubbed, and fixups are registered for later

 *
The modeller runs all the fixups, connecting concrete JTypes with other concrete JTypes.

 *

 *
 * @see Model
 */
public class JacksonTypeModeller implements PropertyEnumerator {

	private static class FixupQueueItem implements Comparable<FixupQueueItem> {

		private final Type type;

		private final int priority;

		private final Consumer<JType> fixup;

		public FixupQueueItem(Type type, int priority, Consumer<JType> fixup) {
			this.type = type;
			this.priority = priority;
			this.fixup = fixup;
		}

		@Override
		public int compareTo(FixupQueueItem o) {
			return Integer.compare(getPriority(), o.getPriority());
		}

		Consumer<JType> getFixup() {
			return fixup;
		}

		int getPriority() {
			return priority;
		}

		public Type getType() {
			return type;
		}
	}

	/**
	 * First pass of fixups - linking fields to their fully-defined types
	 */
	public static final int FIELD_FIXUP_PRIORITY = 1;

	/**
	 * Second pass of fixups - reviewing the model after it is fully defined
	 */
	public static final int MODEL_REVIEW_PRIORITY = 2;

	private static final Logger logger = LoggerFactory.getLogger(JacksonTypeModeller.class);

	/**
	 * Types that are intrinsic to TypeScript
	 */
	private static final Map<Class, Supplier<JType>> FUNDAMENTAL_TYPES = new HashMap<>();

	static {
		FUNDAMENTAL_TYPES.put(Void.class, JVoid::new);
		FUNDAMENTAL_TYPES.put(Void.TYPE, JVoid::new);

		FUNDAMENTAL_TYPES.put(Boolean.class, JBoolean::new);
		FUNDAMENTAL_TYPES.put(Boolean.TYPE, JBoolean::new);

		FUNDAMENTAL_TYPES.put(Byte.class, JNumber::new);
		FUNDAMENTAL_TYPES.put(Byte.TYPE, JNumber::new);
		FUNDAMENTAL_TYPES.put(Short.class, JNumber::new);
		FUNDAMENTAL_TYPES.put(Short.TYPE, JNumber::new);
		FUNDAMENTAL_TYPES.put(Integer.class, JNumber::new);
		FUNDAMENTAL_TYPES.put(Integer.TYPE, JNumber::new);
		FUNDAMENTAL_TYPES.put(Long.class, JNumber::new);
		FUNDAMENTAL_TYPES.put(Long.TYPE, JNumber::new);
		FUNDAMENTAL_TYPES.put(Float.class, JNumber::new);
		FUNDAMENTAL_TYPES.put(Float.TYPE, JNumber::new);
		FUNDAMENTAL_TYPES.put(Double.class, JNumber::new);
		FUNDAMENTAL_TYPES.put(Double.TYPE, JNumber::new);
		FUNDAMENTAL_TYPES.put(BigInteger.class, JNumber::new);
		FUNDAMENTAL_TYPES.put(BigDecimal.class, JNumber::new);

		FUNDAMENTAL_TYPES.put(String.class, JString::new);
		FUNDAMENTAL_TYPES.put(Character.class, JString::new);
		FUNDAMENTAL_TYPES.put(Character.TYPE, JString::new);
	}

	/**
	 * Queue of pending types to process
	 */
	private final ArrayDeque<Type> typesToProcess = new ArrayDeque<>();

	/**
	 * List of fixups to run after ingesting.
	 */
	private final PriorityQueue<FixupQueueItem> typeFixups = new PriorityQueue<>();

	private static final ReflectionsCache reflectionsCache = new ReflectionsCache();

	private final Reflections subclassFinder;

	private final ClassOverrideHandler classOverrides;

	private final boolean includeSubclasses;

	private final String[] packagesToScan;

	private final JEnum.EnumType defaultEnumType;

	/**
	 * Create a modeller.
	 */
	public JacksonTypeModeller(ClassOverrideHandler classOverrides, JEnum.EnumType defaultEnumType, boolean includeSubclasses,
	                           String[] packagesToScan) {
		assert defaultEnumType != null;
		assert packagesToScan != null;
		assert packagesToScan.length > 0;

		this.classOverrides = classOverrides;
		this.defaultEnumType = defaultEnumType;
		this.includeSubclasses = includeSubclasses;
		this.packagesToScan = packagesToScan;

		if (includeSubclasses) {
			subclassFinder = reflectionsCache.getReflections(packagesToScan);
		} else {
			subclassFinder = null;
		}
		// clear list of created types (for debugging)
		JType.createdTypes.clear();
	}

	public static boolean isFundamentalType(Class<?> returnType) {
		return FUNDAMENTAL_TYPES.containsKey(returnType);
	}

	/**
	 * Add a fixup for a given type
	 *
	 * @param type     the type
	 * @param fixup    the fixup to apply
	 * @param priority the priority with which to run the fixup
	 */
	void addFixup(Type type, Consumer<JType> fixup, int priority) {
		typeFixups.add(new FixupQueueItem(type, priority, fixup));
	}

	/**
	 * Add a fixup for a given type (field fixup priority)
	 *
	 * @param type  the type
	 * @param fixup the fixup to apply
	 */
	void addFixup(Type type, Consumer<JType> fixup) {
		addFixup(type, fixup, FIELD_FIXUP_PRIORITY);
	}

	/**
	 * Queue a type for future processing
	 *
	 * @param type
	 */
	void queueType(Type type) {
		typesToProcess.add(type);
	}

	/**
	 * Read Java types into the model.
	 *
	 * @param model the model
	 * @param types the types to add
	 * @return a list of TS types added this run
	 */
	@Override
	public List<JType> readTypes(Model model, Type... types) {

		// enqueue start types
		Collections.addAll(typesToProcess, types);

		// drain the queue
		while (!typesToProcess.isEmpty()) {
			Type type = typesToProcess.pollFirst();
			if (model.hasType(type)) {
				logger.debug("Type {} already seen", type);
				continue;
			}
			logger.debug("Type {} being added", type);
			model.addType(type, handleType(type));
		}
		// apply fixups
		applyFixups(model, typeFixups);

		logger.debug("Done");

		// double-check that all our types wound up in the model
		Collection<JType> interfaces = model.getInterfaces();
		for (JType createdType : JType.createdTypes) {
			if (!interfaces.contains(createdType)) {
				throw new RuntimeException("Type " + createdType + " was created, but it's not in interfaces");
			}
		}

		// find all the TS types created for the type parameters, and return them, in the same order (necessary for #readOneType)
		List<JType> result = new ArrayList<>(types.length);
		for (Type type : types) {
			result.add(model.getType(type));
		}
		return result;
	}

	private void applyFixups(Model model, PriorityQueue<FixupQueueItem> typeCleanups) {
		while (!typeCleanups.isEmpty()) {
			FixupQueueItem fixup = typeCleanups.poll();
			if (fixup != null) {
				JType jType = model.getType(fixup.getType());
				fixup.getFixup().accept(jType);
			}
		}
	}

	/**
	 * Convenience method to process just one type. This may, of course trigger the processing of other types by reference, and they'll
	 * be added to the model, but the other TS types won't be returned.
	 *
	 * @param model the model
	 * @param type  the Java type
	 * @return the TS type
	 */
	@Override
	public JType readOneType(Model model, Type type) {
		return readTypes(model, type).get(0);
	}

	private JType handleType(Type type) {
		logger.debug("Handling {}", type);
		if (type instanceof TypeVariable) {
			// Case 1: type variable
			// Given a type like MyType<T>, the TypeVariable represents T. For a more complex instance like
			// MyType<T extends InterfaceA & InterfaceB>, then InterfaceA and InterfaceB will be in the 'intersectionBounds'. This can be
			// represented in TypeScript, and the syntax is the same.
			logger.debug("is TypeVariable");
			TypeVariable variable = (TypeVariable) type;
			JTypeVariable jVariable = new JTypeVariable(variable.getName());
			// if the bound is only Object, we're going to ignore it
			if (variable.getBounds().length != 1 || variable.getBounds()[0] != Object.class) {
				for (int i = 0; i < variable.getBounds().length; i++) {
					final int finalI = i;
					Type bound = variable.getBounds()[i];
					jVariable.getIntersectionBounds().add(null);
					queueType(bound);
					addFixup(bound, jType -> jVariable.getIntersectionBounds().set(finalI, jType));
				}
			}
			return jVariable;
		} else if (type instanceof ParameterizedType) {
			// Case 2: parametrized type
			// This is for the case of a generic type specialization, where the variables have been specified (e.g. List<Integer>)
			logger.debug("is ParameterizedType");
			ParameterizedType pt = (ParameterizedType) type;
			Type base = pt.getRawType();
			if (isCollection(base)) {
				// Collection<T> -> Array<T>
				JArray result = new JArray();
				result.setIndexType(new JNumber());
				addFixup(pt.getActualTypeArguments()[0], result::setElementType);
				queueType(pt.getActualTypeArguments()[0]);
				return result;
			} else if (isMap(base)) {
				// Map<String, T> -> { [key: string]: T }
				JMap result = new JMap();
				addFixup(pt.getActualTypeArguments()[1], result::setValueType);
				queueType(pt.getActualTypeArguments()[1]);
				return result;
			} else {
				// everything else: A -> A
				JSpecialization jSpecialization = new JSpecialization();
				jSpecialization.setParameters(new JType[pt.getActualTypeArguments().length]);
				addFixup(pt.getRawType(), jSpecialization::setBase);
				queueType(pt.getRawType());
				for (int i = 0; i < pt.getActualTypeArguments().length; i++) {
					final int finalI = i;
					addFixup(pt.getActualTypeArguments()[i], jType -> jSpecialization.getParameters()[finalI] = jType);
					queueType(pt.getActualTypeArguments()[i]);
				}
				return jSpecialization;
			}
		} else if (type instanceof WildcardType) {
			// Case 3: wildcard type
			// This is for the case of a generic type specialization, where the variables have been specified (e.g. List<Integer>)
			logger.debug("is WildcardType");
			WildcardType pt = (WildcardType) type;
			JWildcard jWildcard = new JWildcard();
			Type[] upperBounds = pt.getUpperBounds();
			for (int i = 0; i < upperBounds.length; i++) {
				Type upper = upperBounds[i];
				jWildcard.getUpperBounds().add(null);
				final int idx = i;
				addFixup(upper, (f) -> jWildcard.getUpperBounds().set(idx, f));
				queueType(upper);
			}
			Type[] lowerBounds = pt.getLowerBounds();
			for (int i = 0; i < lowerBounds.length; i++) {
				Type lower = lowerBounds[i];
				jWildcard.getLowerBounds().add(null);
				final int idx = i;
				addFixup(lower, (f) -> jWildcard.getLowerBounds().set(idx, f));
				queueType(lower);
			}
			return jWildcard;
		} else if (type instanceof Class) {
			// Case 3: class (non-generic, plain vanilla)
			logger.debug("is Class");
			Class cl = (Class) type;
			if (cl.isArray()) {
				// array: A[] -> Array
				logger.debug("is array");
				JArray result = new JArray();
				result.setIndexType(new JNumber());
				addFixup(cl.getComponentType(), result::setElementType);
				queueType(cl.getComponentType());
				return result;
			} else {
				if (classOverrides.containsKey(cl)) {
					// substitute class.  If the user created a cycle, sorry.
					Class classOverride = classOverrides.get(cl);
					return handleType(classOverride);
				} else if (FUNDAMENTAL_TYPES.containsKey(type)) {
					// built-in type: int -> number, etc
					logger.debug("is fundamental type");
					return FUNDAMENTAL_TYPES.get(type).get();
				} else {
					// everything else -> interface
					logger.debug("is user-defined class");
					if (includeSubclasses) {
						enqueueSubclasses((Class) type);
					}
					return handleUserDefinedClass((Class) type);
				}
			}
		} else {
			throw new RuntimeException("Can't handle " + type);
		}
	}

	private void enqueueSubclasses(Class<?> type) {
		if (subclassFinder != null) {
			if (type != Object.class) {
				Set<Class<?>> subtypes = subclassFinder.getSubTypesOf((Class<Object>) type);
				for (Class<?> cl : subtypes) {
					queueType(cl);
				}
			}
		}
	}

	/**
	 * Is this Java type a Map? (will turn into an object)
	 *
	 * @param base the type
	 * @return yes or no
	 */
	private static boolean isMap(Type base) {
		return base instanceof Class && Map.class.isAssignableFrom((Class<?>) base);
	}

	/**
	 * Is this Java type a collection? (will turn into an array)
	 *
	 * @param base the type
	 * @return yes or no
	 */
	private static boolean isCollection(Type base) {
		return base instanceof Class && Collection.class.isAssignableFrom((Class<?>) base);
	}

	private JType handleUserDefinedClass(Class type) {

		// Run a Jackson JsonFormatVisitor over our class, let it process all the object properties, and return the resulting JType.
		TypeReadingVisitor<?> reader;
		try {
			ClassReader wrapper = new ClassReader();
			ObjectMapper objectMapper = new ObjectMapper();
			objectMapper.acceptJsonFormatVisitor(type, wrapper);
			reader = wrapper.getReader();
		} catch (JsonMappingException e) {
			throw new RuntimeException(e);
		}
		if (reader == null) {
			return null;
		} else {
			return reader.getResult();
		}
	}

	/**
	 * Jackson format visitor which will be invoked over all the properties.
	 */
	private class ClassReader extends JsonFormatVisitorWrapper.Base {

		private TypeReadingVisitor<?> reader;

		TypeReadingVisitor<?> getReader() {
			return reader;
		}

		@Override
		public JsonArrayFormatVisitor expectArrayFormat(JavaType type) {
			return new JsonArrayFormatVisitor.Base() {
				@Override
				public void itemsFormat(JsonFormatVisitable handler, JavaType elementType) throws JsonMappingException {
					super.itemsFormat(handler, elementType);
				}

				@Override
				public void itemsFormat(JsonFormatTypes format) throws JsonMappingException {
					super.itemsFormat(format);
				}
			};
		}

		@Override
		public JsonStringFormatVisitor expectStringFormat(JavaType type) {
			reader = JString::new;
			return new JsonStringFormatVisitor.Base() {
				@Override
				public void enumTypes(Set<String> enums) {
					reader = () -> {
						Class<?> rawClass = type.getRawClass();
						return buildEnum((Class<Enum<?>>) rawClass);
					};
				}
			};
		}

		@Override
		public JsonNumberFormatVisitor expectNumberFormat(JavaType type) {
			reader = JNumber::new;
			return new JsonNumberFormatVisitor() {
				@Override
				public void numberType(JsonParser.NumberType type) {
					throw new RuntimeException("not implemented");
				}

				@Override
				public void format(JsonValueFormat format) {
					throw new RuntimeException("not implemented");
				}

				@Override
				public void enumTypes(Set<String> enums) {
					throw new RuntimeException("not implemented");
				}
			};
		}

		@Override
		public JsonIntegerFormatVisitor expectIntegerFormat(JavaType type) {
			reader = JNumber::new;
			return new JsonIntegerFormatVisitor.Base() {
			};
		}

		@Override
		public JsonBooleanFormatVisitor expectBooleanFormat(JavaType type) {
			reader = JNumber::new;
			return new JsonBooleanFormatVisitor.Base() {
			};
		}

		@Override
		public JsonNullFormatVisitor expectNullFormat(JavaType type) {
			reader = JNumber::new;
			return new JsonNullFormatVisitor.Base() {
			};
		}

		@Override
		public JsonAnyFormatVisitor expectAnyFormat(JavaType type) {
			reader = JAny::new;
			return new JsonAnyFormatVisitor.Base() {
			};
		}

		@Override
		public JsonMapFormatVisitor expectMapFormat(JavaType type) {
			// We would only have gotten here for a raw map; it's element type is any
			JMap map = new JMap(new JAny());
			reader = () -> map;
			return new JsonMapFormatVisitor.Base() {
			};
		}

		@Override
		public JsonObjectFormatVisitor expectObjectFormat(JavaType type) {
			JsonObjectReader myReader = new JsonObjectReader(JacksonTypeModeller.this, type.getRawClass());
			reader = myReader;
			return myReader;
		}
	}

	private JEnum buildEnum(Class<Enum<?>> rawClass) {
		JEnum.EnumType enumType = null;
		List<JEnum.EnumDeclaration> entries = new ArrayList<>();
		Enum<?>[] constants = rawClass.getEnumConstants();
		Map<String, Enum<?>> usedValues = new HashMap<>();
		for (Enum<?> enumConstant : constants) {

			ObjectMapper objectMapper = new ObjectMapper();
			try {
				String enumConstantValue = objectMapper.writeValueAsString(enumConstant);
				// strip quotes
				int length = enumConstantValue.length();
				if (length > 1 && enumConstantValue.charAt(0) == '"') {
					enumConstantValue = enumConstantValue.substring(1, length - 1);
					if (enumType != null && enumType != JEnum.EnumType.STRING) {
						throw new RuntimeException("Jackson giving both numeric and string values for enum " + rawClass.getName());
					}
					enumType = JEnum.EnumType.STRING;
				} else {
					if (enumType != null && enumType != JEnum.EnumType.NUMERIC) {
						throw new RuntimeException("Jackson giving both numeric and string values for enum " + rawClass.getName());
					}
					enumType = JEnum.EnumType.NUMERIC;
				}

				if (usedValues.containsKey(enumConstantValue)) {
					logger.warn("Computed serialized value of {} to be {}, but that value was also used for {} " +
									"- keeping first definition only",
							new Object[]{enumConstant, enumConstantValue, usedValues.get(enumConstantValue)});
				} else {
					usedValues.put(enumConstantValue, enumConstant);
				}
				entries.add(new JEnum.EnumDeclaration(enumConstant.name(), enumConstant.ordinal(), enumConstantValue));
			} catch (JsonProcessingException e) {
				logger.warn("Couldn not serialize " + enumConstant + ", skipping");
			}
		}
		return new JEnum(rawClass.getName(), enumType == null ? defaultEnumType : enumType, entries);
	}
}


text:
title: Unexplained syntax error on PhantomJS with strict mode
tags: phantomjs, safari, javascript
---

Short story: PhantomJS considers a syntax error when a named function expression is called the same as some of its parameters, and won't be very explicit about it.

READMORE

Consider the following code:

```js
'use strict';
var something = function bug(bug) {};
```

The fact that the function is called `bug`, and the parameter is also called `bug`, will trigger a syntax error in PhantomJS. Note that a function declaration has no problems with it:

```js
'use strict';
function bug(bug) {}
```

No syntax error there! But when there _is_ a syntax error, PhantomJS will only say so and won't specify what the error is. This can be kind of annoying when your automasted tests use Phantom and fail miserably while the app works fine on your browser. One good way to find the cause for these kind of bugs is that PhantomJS behaves very similar to Safari, and this specific bug is also present there. So if you happen to develop on Safari then you'll see it before it gets to Phantom, but if you don't it's a nice trick to remember the next time you have to debug a Phantom-specific bug.

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <title></title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width">

        <link rel="stylesheet" href="css/normalize.css">
        <link rel="stylesheet" href="css/main.css">

		<form>
		    <input type="text" name="ucid" value="UCID">

		    <input type="text" name="pass" value="password">
		    <input type="submit" value="login">
		</form>

  IS392
	    My Courses |
	    Upcoming Events |
	    Activities |
	    Recent Activity |
	    Administration

My Courses

IS101

IS202

IS303

IS392

Upcoming Events
 this will have warnings for imminent assignements

Activities
this will have links to -assignemtns-forums-resources

Recent Activity
info on recent submissions, posts

Administration
 links to grades, profile, people in course

this is where the general things go, like forums, syllabi, etc.  things not associated with a week

syllabus

21 January - 27 January
week 1 info, readings, & announcments

 week 1 assignments

28 January - 3 February
week 2 info & stuff

 week 2 assignments

4 February - 10 February
week 3 etc

 week 3 assignments

11 February - 17 February
week 4 info

 week 3 assignments

18 February - 24 February
week 5 info

 week 3 assignments


text:
                    <button ng-click="query()" ng-disabled="!queryText" class="btn btn-sm btn-success">
                        Run
                    </button>

                    <button ng-click="query(true)" ng-disabled="!queryText" class="btn btn-sm btn-warning">
                        Explain
                    </button>

            <form ng-submit="query()" class="form-inline">

            </form>

                                    Run:
                                    Ctrl + Return
                                    Undo:
                                    Ctrl/Cmd + Z
                                    Redo:
                                    Ctrl/Cmd + Shift + Z

                                        Search :
                                    Ctrl/Cmd + F

                                        Toggle Comment:
                                    Ctrl/Cmd + /

                                        Autocomplete:
                                    Ctrl + Space

                        <form class="form-inline pull-right" ng-show="!hideSettings">
                            <fieldset>

                                    Content Type
                                    <select ng-model="config.selectedContentType" class="form-control input-sm" ng-options="q for q in contentType"></select>

                                    Limit
                                    <input type="text" class="form-control input-sm" ng-model="config.limit">

                                        <input type="checkbox" class="" ng-model="config.hideSettings"> Hide settings

                                <button ng-click="query()" ng-disabled="!queryText" class="btn btn-sm btn-success">
                                    Run
                                </button>

                            </fieldset>
                        </form>

            <form class="form-search search-history" ng-show="timeline.length >1">

                    <input type="text" class="input-xxlarge form-control search-query" ng-model="search.query" placeholder="{{'browse.searchHistory' | translate}}">

                    <button type="submit" data-title="{{'browse.clearHistory' | translate}}" data-animation="am-fade-and-scale" data-placement="right" bs-tooltip="" class="btn" ng-click="clear()">

                    </button>

            </form>

                <button class="btn btn-sm btn-default" data-placement="left" data-title="{{'browse.showBookmark' | translate}}" data-animation="am-fade-and-scale" bs-tooltip="" ng-click="toggleBookmarks()">

                    Bookmarks
                </button>


text:
@interface DYFenceViewController () <AMapGeoFenceManagerDelegate>

@property (nonatomic,strong) AMapGeoFenceManager *geoFenceManager;

@end

@implementation DYFenceViewController

- (void)viewDidLoad {
    [super viewDidLoad];

}

- (void)amapGeoFenceManager:(AMapGeoFenceManager *)manager didAddRegionForMonitoringFinished:(NSArray<AMapGeoFenceRegion *> *)regions customID:(NSString *)customID error:(NSError *)error {

    NSLog(@"regions = %@",regions);

}

- (void)amapGeoFenceManager:(AMapGeoFenceManager *)manager didGeoFencesStatusChangedForRegion:(AMapGeoFenceRegion *)region customID:(NSString *)customID error:(NSError *)error {

    NSLog(@"change");

}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {

    self.geoFenceManager = [[AMapGeoFenceManager alloc] init];
    self.geoFenceManager.delegate = self;
    self.geoFenceManager.activeAction = AMapGeoFenceActiveActionInside | AMapGeoFenceActiveActionOutside | AMapGeoFenceActiveActionStayed; //设置希望侦测的围栏触发行为,默认是侦测用户进入围栏的行为,即AMapGeoFenceActiveActionInside,这边设置为进入,离开,停留(在围栏内10分钟以上),都触发回调
    //self.geoFenceManager.allowsBackgroundLocationUpdates = YES;  //允许后台定位

    [self.geoFenceManager addKeywordPOIRegionForMonitoringWithKeyword:@"北京大学" POIType:@"高等院校" city:@"北京" size:20 customID:@"poi_1"];

    //    CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(39.908692, 116.397477); //天安门
    //    [self.geoFenceManager addAroundPOIRegionForMonitoringWithLocationPoint:coordinate aroundRadius:10000 keyword:@"肯德基" POIType:@"050301" size:20 customID:@"poi_2"];

}

- (void)dealloc {

    NSLog(@"%s", __FUNCTION__);
}
@end


text:
title = 'Subclassing Pmw.Counter'

# Import Pmw from this directory tree.
import sys
sys.path[:0] = ['../../..']

import string
import time
import types
import Tkinter
import Pmw

class LabeledDateCounter(Pmw.Counter):

    def __init__(self, parent=None , **kw):

	# Need to use long ints here because on the Macintosh the maximum size
	# of an integer is smaller than the value returned by time.time().
	now = (long(time.time()) / 300) * 300
        text = time.strftime('%y/%m/%d', time.localtime(now))

        kw['datatype'] = 'date'
        kw['entryfield_validate'] = 'date'
        kw['entryfield_value'] = text
        kw['labelpos'] = 'w'

	apply(Pmw.Counter.__init__, (self, parent), kw)

class LabeledRealCounter(Pmw.Counter):

    def __init__(self, parent=None , **kw):

        # Define the validate option dictionary.
        validate = {'validator' : 'real', 'min' : 0.0, 'max' : 100.0}

        kw['datatype'] = 'real'
        kw['entryfield_validate'] = validate
        kw['entryfield_value'] = 50.0
        kw['labelpos'] = 'w'

	apply(Pmw.Counter.__init__, (self, parent), kw)

class Demo:
    def __init__(self, parent):
	# Create and pack some LabeledDateCounters and LabeledRealCounter.
	self._date1 = LabeledDateCounter(parent, label_text = 'Date:')
	self._date2 = LabeledDateCounter(parent, label_text = 'Another Date:')
	self._real1 = LabeledRealCounter(parent, label_text = 'Real:')
	self._real2 = LabeledRealCounter(parent, label_text = 'Another Real:')

	counters = (self._date1, self._date2, self._real1, self._real2)

	for counter in counters:
	    counter.pack(fill='x', expand=1, padx=10, pady=5)
	Pmw.alignlabels(counters)

######################################################################

# Create demo in root window for testing.
if __name__ == '__main__':
    root = Tkinter.Tk()
    Pmw.initialise(root)
    root.title(title)

    exitButton = Tkinter.Button(root, text = 'Exit', command = root.destroy)
    exitButton.pack(side = 'bottom')
    widget = Demo(root)
    root.mainloop()


text:
package org.jeeventstore.notifier;

import org.jeeventstore.EventStoreCommitListener;
import org.jeeventstore.EventStoreCommitNotification;

public class TestListener implements EventStoreCommitListener {

    public EventStoreCommitNotification notification;

    @Override
    public void receive(EventStoreCommitNotification notification) {
        System.out.println(this + ": received notification: " + notification);
        this.notification = notification;
    }

}


text:
package org.apache.kylin.query.schema;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Collection;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.calcite.schema.Schema;
import org.apache.calcite.schema.SchemaFactory;
import org.apache.calcite.schema.SchemaPlus;
import org.apache.commons.io.FileUtils;
import org.apache.kylin.common.KylinConfig;
import org.apache.kylin.measure.MeasureTypeFactory;
import org.apache.kylin.metadata.model.DatabaseDesc;
import org.apache.kylin.metadata.model.TableDesc;
import org.apache.kylin.metadata.project.ProjectManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.Maps;

/**
 */
public class OLAPSchemaFactory implements SchemaFactory {
    public static final Logger logger = LoggerFactory.getLogger(OLAPSchemaFactory.class);

    private final static String SCHEMA_PROJECT = "project";

    @Override
    public Schema create(SchemaPlus parentSchema, String schemaName, Map<String, Object> operand) {
        String project = (String) operand.get(SCHEMA_PROJECT);
        Schema newSchema = new OLAPSchema(project, schemaName, exposeMore(project));
        return newSchema;
    }

    private static Map<String, File> cachedJsons = Maps.newConcurrentMap();

    public static boolean exposeMore(String project) {
        return ProjectManager.getInstance(KylinConfig.getInstanceFromEnv()).getProject(project).getConfig()
                .isPushDownEnabled();
    }

    public static File createTempOLAPJson(String project, KylinConfig config) {

        ProjectManager projectManager = ProjectManager.getInstance(config);
        KylinConfig projConfig = projectManager.getProject(project).getConfig();
        Collection<TableDesc> tables = projectManager.listExposedTables(project, exposeMore(project));

        // "database" in TableDesc correspond to our schema
        // the logic to decide which schema to be "default" in calcite:
        // if some schema are named "default", use it.
        // other wise use the schema with most tables
        HashMap<String, Integer> schemaCounts = DatabaseDesc.extractDatabaseOccurenceCounts(tables);
        String majoritySchemaName = "";
        int majoritySchemaCount = 0;
        for (Map.Entry<String, Integer> e : schemaCounts.entrySet()) {
            if (e.getKey().equalsIgnoreCase("default")) {
                majoritySchemaCount = Integer.MAX_VALUE;
                majoritySchemaName = e.getKey();
            }

            if (e.getValue() >= majoritySchemaCount) {
                majoritySchemaCount = e.getValue();
                majoritySchemaName = e.getKey();
            }
        }

        try {

            StringBuilder out = new StringBuilder();
            out.append("{\n");
            out.append("    \"version\": \"1.0\",\n");
            out.append("    \"defaultSchema\": \"" + majoritySchemaName + "\",\n");
            out.append("    \"schemas\": [\n");

            int counter = 0;

            String schemaFactory = projConfig.getSchemaFactory();
            for (String schemaName : schemaCounts.keySet()) {
                out.append("        {\n");
                out.append("            \"type\": \"custom\",\n");
                out.append("            \"name\": \"" + schemaName + "\",\n");
                out.append("            \"factory\": \"" + schemaFactory + "\",\n");
                out.append("            \"operand\": {\n");
                out.append("                \"" + SCHEMA_PROJECT + "\": \"" + project + "\"\n");
                out.append("            },\n");
                createOLAPSchemaFunctions(projConfig.getUDFs(), out);
                out.append("        }\n");

                if (++counter != schemaCounts.size()) {
                    out.append(",\n");
                }
            }

            out.append("    ]\n");
            out.append("}\n");

            String jsonContent = out.toString();
            File file = cachedJsons.get(jsonContent);
            if (file == null) {
                file = Files.createTempFile("olap_model_", ".json").toFile();
                file.deleteOnExit();
                FileUtils.writeStringToFile(file, jsonContent);

                logger.debug("Adding new schema file {} to cache", file.getName());
                logger.debug("Schema json: " + jsonContent);
                cachedJsons.put(jsonContent, file);
            }

            return file;

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private static void createOLAPSchemaFunctions(Map<String, String> definedUdfs, StringBuilder out)
            throws IOException {
        Map<String, String> udfs = Maps.newHashMap();
        if (definedUdfs != null)
            udfs.putAll(definedUdfs);

        for (Entry<String, Class<?>> entry : MeasureTypeFactory.getUDAFs().entrySet()) {
            udfs.put(entry.getKey(), entry.getValue().getName());
        }

        int index = 0;
        out.append("            \"functions\": [\n");
        for (Map.Entry<String, String> udf : udfs.entrySet()) {
            String udfName = udf.getKey().trim().toUpperCase(Locale.ROOT);
            String udfClassName = udf.getValue().trim();
            out.append("               {\n");
            out.append("                   name: '" + udfName + "',\n");
            out.append("                   className: '" + udfClassName + "'\n");
            if (index < udfs.size() - 1) {
                out.append("               },\n");
            } else {
                out.append("               }\n");
            }
            index++;
        }
        out.append("            ]\n");
    }
}


text:
A handy encode/decode tool for multiple formats.

Encoding Smith is a Chrome extension utility handles multiple encoding methods. Encode/decode to multiple formats at same time and does not require Internet connection.

---

## Structures

### Chosen Technology
* Sass
* Gulp
* Browser Sync
* Lodash
* [Bows](https://github.com/latentflip/bows)

---

## Build

### Prerequisites
* Node.js and NPM
* gulp NPM module

### First Build
* Execute `npm install`
* Execute `gulp` which will perform 'build' and starts 'watch' and 'server' tasks.

---

## Resources
* Use Revox as design guide: http://pages.revox.io/dashboard/latest/html/form_elements.html

* HTML Entity Encoder: http://www.w3schools.com/tags/ref_urlencode.asp
* Upside Down: http://www.web2generators.com/text-related-tools/write-upside-down
* HTPasswd Generator: http://www.web2generators.com/apache-tools/htpasswd-generator
* MD5 encode/decode tool: http://md5decrypt.net/en/
* Various of character encoding/escaping: http://www.the-art-of-web.com/javascript/escape/
* Various of checksum methods: http://codepen.io/ImagineProgramming/post/checksum-algorithms-in-javascript-checksum-js-engine

## Test Cases
* TBA

---

## Progress

### New incoming supports
* Upside Down text
* Zalgo (http://stackoverflow.com/questions/6579844/how-does-zalgo-text-work)
* TEA (different versions)

### Todo List
* Add favicon
* Avoid calculate encoding options that are set to hidden, however make sure that when the option been toggled to enbale, the encoded value is avaiable/current.
* Error notification when something's wrong

### Backburner
* Save user's toggle option

### Roadmaps
* TBA


text:
package com.arialyy.frame.util;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.text.TextUtils;

import com.google.gson.Gson;

/**
 * 配置文件工具类
 *
 * @author Administrator
 */
public class SharePreUtil {

  /**
   * 删除键值对
   */
  public static void removeKey(String preName, Context context, String key) {
    SharedPreferences pre = context.getSharedPreferences(preName, Context.MODE_PRIVATE);
    Editor editor = pre.edit();
    editor.remove(key);
    editor.commit();
  }

  /**
   * 从配置文件读取字符串
   *
   * @param preName 配置文件名
   * @param key 字符串键值
   * @return 键值对应的字符串, 默认返回""
   */
  public static String getString(String preName, Context context, String key) {
    SharedPreferences pre = context.getSharedPreferences(preName, Context.MODE_PRIVATE);
    return pre.getString(key, "");
  }

  /**
   * 从配置文件读取int数据
   *
   * @param preName 配置文件名
   * @param key int的键值
   * @return 键值对应的int, 默认返回-1
   */
  public static int getInt(String preName, Context context, String key) {
    SharedPreferences pre = context.getSharedPreferences(preName, Context.MODE_PRIVATE);
    return pre.getInt(key, -1);
  }

  /**
   * 从配置文件读取Boolean值
   *
   * @return 如果没有,默认返回false
   */
  public static Boolean getBoolean(String preName, Context context, String key) {
    SharedPreferences pre = context.getSharedPreferences(preName, Context.MODE_PRIVATE);
    return pre.getBoolean(key, false);
  }

  /**
   * 从配置文件获取float数据
   *
   * @return 默认返回0.0f
   */
  public static float getFloat(String preName, Context context, String key) {
    SharedPreferences pre = context.getSharedPreferences(preName, Context.MODE_PRIVATE);
    return pre.getFloat(key, 0.0f);
  }

  /**
   * 从配置文件获取对象
   */
  public static <T> T getObject(String preName, Context context, String key, Class<T> clazz) {
    SharedPreferences pre = context.getSharedPreferences(preName, Context.MODE_PRIVATE);
    String str = pre.getString(key, "");
    return TextUtils.isEmpty(str) ? null : new Gson().fromJson(str, clazz);
  }

  /**
   * 存储字符串到配置文件
   *
   * @param preName 配置文件名
   * @param key 存储的键值
   * @param value 需要存储的字符串
   * @return 成功标志
   */
  public static Boolean putString(String preName, Context context, String key, String value) {
    SharedPreferences pre = context.getSharedPreferences(preName, Context.MODE_PRIVATE);
    Editor editor = pre.edit();
    editor.putString(key, value);
    return editor.commit();
  }

  /**
   * 保存Float数据到配置文件
   */
  public static Boolean putFloat(String preName, Context context, String key, float value) {
    SharedPreferences pre = context.getSharedPreferences(preName, Context.MODE_PRIVATE);
    Editor editor = pre.edit();
    editor.putFloat(key, value);
    return editor.commit();
  }

  /**
   * 存储数字到配置文件
   *
   * @param preName 配置文件名
   * @param key 存储的键值
   * @param value 需要存储的数字
   * @return 成功标志
   */
  public static Boolean putInt(String preName, Context context, String key, int value) {
    SharedPreferences pre = context.getSharedPreferences(preName, Context.MODE_PRIVATE);
    Editor editor = pre.edit();
    editor.putInt(key, value);
    return editor.commit();
  }

  /**
   * 存储Boolean值到配置文件
   *
   * @param preName 配置文件名
   * @param key 键值
   * @param value 需要存储的boolean值
   */
  public static Boolean putBoolean(String preName, Context context, String key, Boolean value) {
    SharedPreferences pre = context.getSharedPreferences(preName, Context.MODE_PRIVATE);
    Editor editor = pre.edit();
    editor.putBoolean(key, value);
    return editor.commit();
  }

  /**
   * 存放对象
   */
  public static Boolean putObject(String preName, Context context, String key, Class<?> clazz,
      Object obj) {
    String str = new Gson().toJson(obj, clazz);
    SharedPreferences pre = context.getSharedPreferences(preName, Context.MODE_PRIVATE);
    Editor editor = pre.edit();
    editor.putString(key, str);
    return editor.commit();
  }
}


text:
package net.fhannes.rx.collections;

import io.reactivex.Observable;
import io.reactivex.subjects.BehaviorSubject;
import io.reactivex.subjects.PublishSubject;
import net.fhannes.rx.collections.util.EntryChange;
import net.fhannes.rx.collections.util.ImmutableEntry;

import java.util.*;

public class ObservableMap<K, V> implements Map<K, V> {

    private Map<K, V> map;
    private BehaviorSubject<Map<K, V>> items = BehaviorSubject.create();
    private PublishSubject<Map.Entry<K, V>> put = PublishSubject.create();
    private PublishSubject<Map.Entry<K, V>> added = PublishSubject.create();
    private PublishSubject<Map.Entry<K, V>> removed = PublishSubject.create();
    private PublishSubject<EntryChange<K, V>> updated = PublishSubject.create();

    private boolean updating = false;

    private void changed() {
        if (!updating) {
            items.onNext(Collections.unmodifiableMap(new HashMap<>(this)));
        }
    }

    private void beginUpdate() {
        updating = true;
    }

    private void endUpdate(boolean changed) {
        updating = false;
        if (changed) {
            changed();
        }
    }

    ObservableMap(Map<K, V> map) {
        this.map = map;
        changed();
    }

    /**
     * Returns the map used internally to store elements.
     */
    Map<K, V> getList() {
        return map;
    }

    @Override
    public int size() {
        return map.size();
    }

    @Override
    public boolean isEmpty() {
        return map.isEmpty();
    }

    @Override
    public boolean containsKey(Object key) {
        return map.containsKey(key);
    }

    @Override
    public boolean containsValue(Object value) {
        return map.containsValue(value);
    }

    @Override
    public V get(Object key) {
        return map.get(key);
    }

    @Override
    public V put(K key, V value) {
        boolean keyExists = map.containsKey(key);
        V oldValue = map.put(key, value);
        put.onNext(ImmutableEntry.of(key, value));
        if (keyExists) {
            updated.onNext(EntryChange.of(key, oldValue, value));
        } else {
            added.onNext(ImmutableEntry.of(key, value));
        }
        changed();
        return value;
    }

    @Override
    public V remove(Object key) {
        V value = map.remove(key);
        removed.onNext(ImmutableEntry.of((K) key, value));
        changed();
        return value;
    }

    @Override
    public void putAll(Map<? extends K, ? extends V> m) {
        beginUpdate();
        try {
            m.forEach(this::put);
        } finally {
            endUpdate(!m.isEmpty());
        }
    }

    @Override
    public void clear() {
        map.clear();
        map.forEach((k, v) -> removed.onNext(ImmutableEntry.of(k, v)));
        changed();
    }

    @Override
    public Set<K> keySet() {
        return map.keySet();
    }

    @Override
    public Collection<V> values() {
        return map.values();
    }

    @Override
    public Set<Entry<K, V>> entrySet() {
        return map.entrySet();
    }

    public Observable<Entry<K, V>> observable() {
        return Observable.fromIterable(map.entrySet());
    }

    public Observable<Map<K, V>> observableChanges() {
        return Observable.wrap(items);
    }

    private Observable<Map.Entry<K, V>> onPut() {
        return Observable.wrap(put);
    }

    private Observable<Map.Entry<K, V>> onAdded() {
        return Observable.wrap(added);
    }

    private Observable<Map.Entry<K, V>> onRemoved() {
        return Observable.wrap(removed);
    }

    private Observable<EntryChange<K, V>> onUpdated() {
        return Observable.wrap(updated);
    }

}


text:
<?php
/**
 * @package dompdf
 * @link    http://dompdf.github.com/
 * @author  Benj Carson <benjcarson@digitaljunkies.ca>
 * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
 */

namespace Dompdf\Positioner;

use Dompdf\FrameDecorator\AbstractFrameDecorator;

/**
 * Dummy positioner
 *
 * @package dompdf
 */
class NullPositioner extends AbstractPositioner
{

    function __construct(AbstractFrameDecorator $frame)
    {
        parent::__construct($frame);
    }

    function position()
    {
        return;
    }

}


text:
from .creative_work import CreativeWork

class WebPage(CreativeWork):
    """Defines a webpage that is relevant to the query.

    Variables are only populated by the server, and will be ignored when
    sending a request.

    :param _type: Constant filled by server.
    :type _type: str
    :ivar id: A String identifier.
    :vartype id: str
    :ivar web_search_url: The URL To Bing's search result for this item.
    :vartype web_search_url: str
    :ivar name: The name of the thing represented by this object.
    :vartype name: str
    :ivar url: The URL to get more information about the thing represented by
     this object.
    :vartype url: str
    :ivar image:
    :vartype image:
     ~azure.cognitiveservices.search.websearch.models.ImageObject
    :ivar description: A short description of the item.
    :vartype description: str
    :ivar bing_id: An ID that uniquely identifies this item.
    :vartype bing_id: str
    :ivar thumbnail_url: The URL to a thumbnail of the item.
    :vartype thumbnail_url: str
    :ivar provider: The source of the creative work.
    :vartype provider:
     list[~azure.cognitiveservices.search.websearch.models.Thing]
    :ivar text:
    :vartype text: str
    :ivar display_url: The display URL of the webpage. The URL is meant for
     display purposes only and is not well formed.
    :vartype display_url: str
    :ivar snippet: A snippet of text from the webpage that describes its
     contents.
    :vartype snippet: str
    :ivar deep_links: A list of links to related content that Bing found in
     the website that contains this webpage. The Webpage object in this context
     includes only the name, url, urlPingSuffix, and snippet fields.
    :vartype deep_links:
     list[~azure.cognitiveservices.search.websearch.models.WebPage]
    :ivar date_last_crawled: The last time that Bing crawled the webpage. The
     date is in the form, YYYY-MM-DDTHH:MM:SS. For example,
     2015-04-13T05:23:39.
    :vartype date_last_crawled: str
    :ivar search_tags: A list of search tags that the webpage owner specified
     on the webpage. The API returns only indexed search tags. The name field
     of the MetaTag object contains the indexed search tag. Search tags begin
     with search.* (for example, search.assetId). The content field contains
     the tag's value.
    :vartype search_tags:
     list[~azure.cognitiveservices.search.websearch.models.WebMetaTag]
    :ivar primary_image_of_page:
    :vartype primary_image_of_page:
     ~azure.cognitiveservices.search.websearch.models.ImageObject
    """

    _validation = {
        '_type': {'required': True},
        'id': {'readonly': True},
        'web_search_url': {'readonly': True},
        'name': {'readonly': True},
        'url': {'readonly': True},
        'image': {'readonly': True},
        'description': {'readonly': True},
        'bing_id': {'readonly': True},
        'thumbnail_url': {'readonly': True},
        'provider': {'readonly': True},
        'text': {'readonly': True},
        'display_url': {'readonly': True},
        'snippet': {'readonly': True},
        'deep_links': {'readonly': True},
        'date_last_crawled': {'readonly': True},
        'search_tags': {'readonly': True},
        'primary_image_of_page': {'readonly': True},
    }

    _attribute_map = {
        '_type': {'key': '_type', 'type': 'str'},
        'id': {'key': 'id', 'type': 'str'},
        'web_search_url': {'key': 'webSearchUrl', 'type': 'str'},
        'name': {'key': 'name', 'type': 'str'},
        'url': {'key': 'url', 'type': 'str'},
        'image': {'key': 'image', 'type': 'ImageObject'},
        'description': {'key': 'description', 'type': 'str'},
        'bing_id': {'key': 'bingId', 'type': 'str'},
        'thumbnail_url': {'key': 'thumbnailUrl', 'type': 'str'},
        'provider': {'key': 'provider', 'type': '[Thing]'},
        'text': {'key': 'text', 'type': 'str'},
        'display_url': {'key': 'displayUrl', 'type': 'str'},
        'snippet': {'key': 'snippet', 'type': 'str'},
        'deep_links': {'key': 'deepLinks', 'type': '[WebPage]'},
        'date_last_crawled': {'key': 'dateLastCrawled', 'type': 'str'},
        'search_tags': {'key': 'searchTags', 'type': '[WebMetaTag]'},
        'primary_image_of_page': {'key': 'primaryImageOfPage', 'type': 'ImageObject'},
    }

    def __init__(self):
        super(WebPage, self).__init__()
        self.display_url = None
        self.snippet = None
        self.deep_links = None
        self.date_last_crawled = None
        self.search_tags = None
        self.primary_image_of_page = None
        self._type = 'WebPage'


text:
> Markdown parser

[![npm version](https://img.shields.io/npm/v/mos-core.svg?style=flat-square)](https://www.npmjs.com/package/mos-core) [![Build Status](https://img.shields.io/travis/mosjs/mos-core/master.svg?style=flat-square)](https://travis-ci.org/mosjs/mos-core) [![Coverage Status](https://img.shields.io/coveralls/mosjs/mos-core/master.svg?style=flat-square)](https://coveralls.io/r/mosjs/mos-core?branch=master)

## Installation

```sh
npm install --save mos-core
```

## Usage

```js
const mosCore = require('mos-core')
```

## License

[MIT](./LICENSE) © [Zoltan Kochan](http://kochan.io)

* * *

## Dependencies [![dependency status](https://img.shields.io/david/mosjs/mos-core/master.svg?style=flat-square)](https://david-dm.org/mosjs/mos-core/master)

- [babel-run-async](https://github.com/zkochan/run-async): Utility method to run function either synchronously or asynchronously using the common `this.async()` style.
- [babel-runtime](https://github.com/babel/babel/blob/master/packages): babel selfContained runtime
- [ccount](https://github.com/wooorm/ccount): Count characters
- [collapse-white-space](https://github.com/wooorm/collapse-white-space): Replace multiple white-space characters with a single space
- [core-js](https://github.com/zloirock/core-js): Standard library
- [file-position](https://github.com/hughsk/file-position): Given a row/column number, return the index of that character within the whole string
- [longest-streak](https://github.com/wooorm/longest-streak): Count the longest repeating streak of a character
- [markdown-table](https://github.com/wooorm/markdown-table): Markdown/ASCII tables
- [parse-entities](https://github.com/wooorm/parse-entities): Parse HTML character references: fast, spec-compliant, positional information
- [stringify-entities](https://github.com/wooorm/stringify-entities): Encode HTML character references and character entities
- [trim-trailing-lines](https://github.com/wooorm/trim-trailing-lines): Remove final newline characters from a string
- [unist-util-remove-position](https://github.com/wooorm/unist-util-remove-position): Remove `position`s from a unist tree

## Dev Dependencies [![devDependency status](https://img.shields.io/david/dev/mosjs/mos-core/master.svg?style=flat-square)](https://david-dm.org/mosjs/mos-core/master#info=devDependencies)

- [babel-cli](https://github.com/babel/babel/blob/master/packages): Babel command line.
- [babel-plugin-add-module-exports](https://github.com/59naga/babel-plugin-add-module-exports): Fix babel/babel#2212
- [babel-plugin-transform-runtime](https://github.com/babel/babel/blob/master/packages): Externalise references to helpers and builtins, automatically polyfilling your code without polluting globals
- [babel-preset-es2015](https://github.com/babel/babel/blob/master/packages): Babel preset for all es2015 plugins.
- [babel-register](https://github.com/babel/babel/blob/master/packages): babel require hook
- [camelcase](https://github.com/sindresorhus/camelcase): Convert a dash/dot/underscore/space separated string to camelCase: foo-bar → fooBar
- [chai](https://github.com/chaijs/chai): BDD/TDD assertion library for node.js and the browser. Test framework agnostic.
- [clone](https://github.com/pvorb/node-clone): deep cloning of objects and arrays
- [cz-conventional-changelog](https://github.com/commitizen/cz-conventional-changelog): Commitizen adapter following the conventional-changelog format.
- [eslint](https://github.com/eslint/eslint): An AST-based pattern checker for JavaScript.
- [eslint-config-standard](https://github.com/feross/eslint-config-standard): JavaScript Standard Style - ESLint Shareable Config
- [eslint-plugin-promise](https://github.com/xjamundx/eslint-plugin-promise): Enforce best practices for JavaScript promises
- [eslint-plugin-standard](https://github.com/xjamundx/eslint-plugin-standard): ESlint Plugin for the Standard Linter
- [extend](https://github.com/justmoon/node-extend): Port of jQuery.extend for node.js and the browser
- [ghooks](https://github.com/gtramontina/ghooks): Simple git hooks
- [istanbul](https://github.com/gotwarlost/istanbul): Yet another JS code coverage tool that computes statement, line, function and branch coverage with module loader hooks to transparently add coverage when running tests. Supports all JS coverage use cases including unit tests, server side functional tests
- [mocha](https://github.com/mochajs/mocha): simple, flexible, fun test framework
- [mos](https://github.com/mosjs/mos): A pluggable module that injects content into your markdown files via hidden JavaScript snippets
- [mos-plugin-readme](https://github.com/mosjs/mos-plugin-readme): A mos plugin for generating README
- [semantic-release](https://github.com/semantic-release/semantic-release): automated semver compliant package publishing
- [tslint](https://github.com/palantir/tslint): An extensible static analysis linter for the TypeScript language
- [typescript](https://github.com/Microsoft/TypeScript): TypeScript is a language for application scale JavaScript development
- [validate-commit-msg](https://github.com/kentcdodds/validate-commit-msg): Script to validate a commit message follows the conventional changelog standard


text:
/*jslint node: true */

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

var log = require("./logging.js").log;
var prettyLog = require("./logging.js").prettyLog;

var showHelp = function(modes) {
    var optionsText;
    var modeKey;
    var optionKey;
    prettyLog("The following options are available: ");
    for (modeKey in modes) {
        if (modes.hasOwnProperty(modeKey)) {
            var mode = modes[modeKey];
            optionsText = "";
            for (optionKey in mode.options) {
                if (mode.options.hasOwnProperty(optionKey)) {
                    optionsText += mode.options[optionKey] + "/";
                }
            }
            if (optionsText !== "") {
                optionsText = optionsText.substr(0, optionsText.length - 1);
                optionsText = "[" + optionsText + "]";
            }
            log(mode.value + " " + optionsText + "    " + mode.description);
        }
    }
    log("");
};

module.exports = showHelp;


text:
namespace GLib {

	using System;
	using System.Collections;
	using System.Runtime.InteropServices;

#region Autogenerated code
	public class InetSocketAddress : GLib.Opaque {

		public InetSocketAddress(IntPtr raw) : base(raw) {}

#endregion
	}
}


text:
import os
import sys
import base64
import uuid
import socket
import time
import json
import requests as rq

from kunai.log import cprint, logger
from kunai.version import VERSION

# Will be populated by the shinken CLI command
CONFIG = None

HOSTNAME = socket.gethostname()

############# ********************        MEMBERS management          ****************###########

def do_members():
    try:
        r = rq.get('http://%s:6768/agent/members' % HOSTNAME)
    except rq.exceptions.ConnectionError, exp:
        logger.error(exp)
        return
    try:
        members = json.loads(r.text).values()
    except ValueError, exp:# bad json
        logger.error('Bad return from the server %s' % exp)
        return
    members = sorted(members, key=lambda e:e['name'])
    for m in members:
        name = m['name']
        tags = m['tags']
        port = m['port']
        addr = m['addr']
        state = m['state']
        cprint('%s ' % name, end='')
        c = {'alive':'green', 'dead':'red', 'suspect':'yellow', 'leave':'cyan'}.get(state, 'cyan')
        cprint(state, color=c, end='')
        cprint(' %s:%s' % (addr, port), end='')
        cprint(' %s ' % ','.join(tags))

def do_leave(name=''):
    # Lookup at the localhost name first
    if not name:
        try:
            r = rq.get('http://%s:6768/agent/name' % HOSTNAME)
        except rq.exceptions.ConnectionError, exp:
            logger.error(exp)
            return
        name = r.text
    try:
        r = rq.get('http://%s:6768/agent/leave/%s' % (HOSTNAME, name))
    except rq.exceptions.ConnectionError, exp:
        logger.error(exp)
        return
    if r.status_code != 200:
        logger.error('Node %s is missing' % name)
        print r.text
        return
    cprint('Node %s is set to leave state' % name,end='')
    cprint(': OK', color='green')

def do_state(name=''):
    uri = 'http://%s:6768/agent/state/%s' % (HOSTNAME, name)
    if not name:
        uri = 'http://%s:6768/agent/state' % HOSTNAME
    try:
        r = rq.get(uri)
    except rq.exceptions.ConnectionError, exp:
        logger.error(exp)
        return

    try:
        d = json.loads(r.text)
    except ValueError, exp:# bad json
        logger.error('Bad return from the server %s' % exp)
        return

    print 'Services:'
    for (sname, service) in d['services'].iteritems():
        state = service['state_id']
        cprint('\t%s ' % sname.ljust(20),end='')
        c = {0:'green', 2:'red', 1:'yellow', 3:'cyan'}.get(state, 'cyan')
        state = {0:'OK', 2:'CRITICAL', 1:'WARNING', 3:'UNKNOWN'}.get(state, 'UNKNOWN')
        cprint('%s - ' % state.ljust(8), color=c, end='')
        output = service['check']['output']
        cprint(output.strip())

    print "Checks:"
    for (cname, check) in d['checks'].iteritems():
        state = check['state_id']
        cprint('\t%s ' % cname.ljust(20),end='')
        c = {0:'green', 2:'red', 1:'yellow', 3:'cyan'}.get(state, 'cyan')
        state = {0:'OK', 2:'CRITICAL', 1:'WARNING', 3:'UNKNOWN'}.get(state, 'UNKNOWN')
        cprint('%s - ' % state.ljust(8), color=c, end='')
        output = check['output']
        cprint(output.strip())

def do_version():
    cprint(VERSION)

def do_join(seed=''):
    if seed == '':
        logger.error('Missing target argument. For example 192.168.0.1:6768')
        return
    try:
        r = rq.get('http://%s:6768/agent/join/%s' % (HOSTNAME, seed))
    except rq.exceptions.ConnectionError, exp:
        logger.error(exp)
        return
    try:
        b = json.loads(r.text)
    except ValueError, exp:# bad json
        logger.error('Bad return from the server %s' % exp)
        return
    cprint('Joining %s : ' % seed, end='')
    if b:
        cprint('OK', color='green')
    else:
        cprint('FAILED', color='red')

def do_keygen():
    k = uuid.uuid1().hex[:16]
    cprint('UDP Encryption key: (aka encryption_key)', end='')
    cprint(base64.b64encode(k), color='green')
    print ''
    try:
        from Crypto.PublicKey import RSA
    except ImportError:
        logger.error('Missing python-crypto module for RSA keys generation, please install it')
        return
    key = RSA.generate(2048)
    privkey = key.exportKey()
    pub_key = key.publickey()
    pubkey = pub_key.exportKey()
    print "Private RSA key (2048). (aka master_key_priv for for file mfkey.priv)"
    cprint(privkey, color='green')
    print ''
    print "Public RSA key (2048). (aka master_key_pub for file mfkey.pub)"
    cprint(pubkey, color='green')
    print ''

def do_exec(tag='*', cmd='uname -a'):
    if cmd == '':
        logger.error('Missing command')
        return
    try:
        r = rq.get('http://%s:6768/exec/%s?cmd=%s' % (HOSTNAME, tag, cmd))
    except rq.exceptions.ConnectionError, exp:
        logger.error(exp)
        return
    print r
    cid = r.text
    print "Command group launch as cid", cid
    time.sleep(5) # TODO: manage a real way to get the result..
    try:
        r = rq.get('http://%s:6768/exec-get/%s' % (HOSTNAME, cid))
    except rq.exceptions.ConnectionError, exp:
        logger.error(exp)
        return
    j = json.loads(r.text)
    print j
    res = j['res']
    for (uuid, e) in res.iteritems():
        node = e['node']
        nname = node['name']
        color = {'alive':'green', 'dead':'red', 'suspect':'yellow', 'leave':'cyan'}.get(node['state'], 'cyan')
        cprint(nname, color=color)
        cprint('Return code:', end='')
        color = {0:'green', 1:'yellow', 2:'red'}.get(e['rc'], 'cyan')
        cprint(e['rc'], color=color)
        cprint('Output:', end='')
        cprint(e['output'].strip(), color=color)
        if e['err']:
            cprint('Error:', end='')
            cprint(e['err'].strip(), color='red')
        print ''

exports = {
    do_members : {
        'keywords': ['members'],
        'args': [],
        'description': 'List the cluster members'
        },
    do_version : {
        'keywords': ['version'],
        'args': [],
        'description': 'Print the daemon version'
        },
    do_keygen : {
        'keywords': ['keygen'],
        'args': [],
        'description': 'Generate a encryption key'
        },
    do_exec : {
        'keywords': ['exec'],
        'args': [
            {'name' : 'tag', 'default':'', 'description':'Name of the node tag to execute command on'},
            {'name' : 'cmd', 'default':'uname -a', 'description':'Command to run on the nodes'},
            ],
        'description': 'Execute a command (default to uname -a) on a group of node of the good tag (default to all)'
        },

    do_join : {
        'keywords': ['join'],
        'description': 'Join another node cluster',
        'args': [
            {'name' : 'seed', 'default':'', 'description':'Other node to join. For example 192.168.0.1:6768'},
            ],
        },

    do_leave : {
        'keywords': ['leave'],
        'description': 'Join another node cluster',
        'args': [
            {'name' : 'name', 'default':'', 'description':'Name of the node to force leave. If void, leave our local node'},
            ],
        },

    do_state : {
        'keywords': ['state'],
        'description': 'Print the state of a node',
        'args': [
            {'name' : 'name', 'default':'', 'description':'Name of the node to print state. If void, take our localhost one'},
            ],
        },

    }


text:
package org.apache.batik.svggen.font.table;

import java.io.IOException;
import java.io.RandomAccessFile;

/**
 *
 * @author David Schweinsberg
 * @version $Id: FeatureRecord.java 475477 2006-11-15 22:44:28Z cam $
 */
public class FeatureRecord {

    private int tag;
    private int offset;

    /** Creates new FeatureRecord */
    public FeatureRecord(RandomAccessFile raf) throws IOException {
        tag = raf.readInt();
        offset = raf.readUnsignedShort();
    }

    public int getTag() {
        return tag;
    }

    public int getOffset() {
        return offset;
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<ProjectOutput Name="CraniumSync" ProjectDirVar="$(var.CraniumSync.ProjectDir)" TargetDirVar="$(var.CraniumSync.TargetDir)" SharedFileId="_8899A981_0037_49BD_B775_84CF2C50760B">
  <Binaries>
    <DiskId>1</DiskId>
    <Compressed />
    <Hidden>no</Hidden>
    <KeyPath>yes</KeyPath>
    <ReadOnly>no</ReadOnly>
    <System>no</System>
    <Vital>yes</Vital>
    <Condition><![CDATA[]]></Condition>
    <SelfRegCost />
    <TrueType>no</TrueType>
    <Permanent>no</Permanent>
    <SharedDllRefCount>no</SharedDllRefCount>
    <Transitive>no</Transitive>
  </Binaries>
  <Symbols>
    <DiskId>1</DiskId>
    <Compressed />
    <Hidden>no</Hidden>
    <KeyPath>yes</KeyPath>
    <ReadOnly>no</ReadOnly>
    <System>no</System>
    <Vital>yes</Vital>
    <Condition><![CDATA[]]></Condition>
    <SelfRegCost />
    <TrueType>no</TrueType>
    <Permanent>no</Permanent>
    <SharedDllRefCount>no</SharedDllRefCount>
    <Transitive>no</Transitive>
  </Symbols>
  <Sources>
    <DiskId>1</DiskId>
    <Compressed />
    <Hidden>no</Hidden>
    <KeyPath>yes</KeyPath>
    <ReadOnly>no</ReadOnly>
    <System>no</System>
    <Vital>yes</Vital>
    <Condition><![CDATA[]]></Condition>
    <SelfRegCost />
    <TrueType>no</TrueType>
    <Permanent>no</Permanent>
    <SharedDllRefCount>no</SharedDllRefCount>
    <Transitive>no</Transitive>
  </Sources>
  <Content>
    <DiskId>1</DiskId>
    <Compressed />
    <Hidden>no</Hidden>
    <KeyPath>yes</KeyPath>
    <ReadOnly>no</ReadOnly>
    <System>no</System>
    <Vital>yes</Vital>
    <Condition><![CDATA[]]></Condition>
    <SelfRegCost />
    <TrueType>no</TrueType>
    <Permanent>no</Permanent>
    <SharedDllRefCount>no</SharedDllRefCount>
    <Transitive>no</Transitive>
  </Content>
  <Satellites>
    <DiskId>1</DiskId>
    <Compressed />
    <Hidden>no</Hidden>
    <KeyPath>yes</KeyPath>
    <ReadOnly>no</ReadOnly>
    <System>no</System>
    <Vital>yes</Vital>
    <Condition><![CDATA[]]></Condition>
    <SelfRegCost />
    <TrueType>no</TrueType>
    <Permanent>no</Permanent>
    <SharedDllRefCount>no</SharedDllRefCount>
    <Transitive>no</Transitive>
  </Satellites>
  <Documents>
    <DiskId>1</DiskId>
    <Compressed />
    <Hidden>no</Hidden>
    <KeyPath>yes</KeyPath>
    <ReadOnly>no</ReadOnly>
    <System>no</System>
    <Vital>yes</Vital>
    <Condition><![CDATA[]]></Condition>
    <SelfRegCost />
    <TrueType>no</TrueType>
    <Permanent>no</Permanent>
    <SharedDllRefCount>no</SharedDllRefCount>
    <Transitive>no</Transitive>
  </Documents>
</ProjectOutput>


text:
{% include svg-icons.html %}

{% if site.footer-text %}
<p>{{ site.footer-text }}</p>
{% endif %}


text: export { default } from 'ember-cli-appkit/serializers/appkit';


text:
#pragma once

#include "glTFForUE4PublicPCH.h"

#if GLTFFORUE_ENGINE_VERSION < 415
#include <Core.h>
#include <CoreUObject.h>
#include <Engine.h>
#else
#include <CoreMinimal.h>
#endif

DECLARE_LOG_CATEGORY_EXTERN(LogglTFForUE4Ed, Log, All);


text:
package com.opengamma.financial.comparison;

import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.Set;

import com.google.common.collect.Sets;
import com.opengamma.core.position.Position;
import com.opengamma.core.position.Trade;

/* package */final class PositionInfo extends PositionOrTradeInfo<Position> {

  private final Set<TradeInfo> _trades;

  private final Map<String, String> _attributes;

  public PositionInfo(final ComparisonContext context, final Position position) {
    super(context, position);
    final Collection<Trade> trades = position.getTrades();
    if (trades.isEmpty()) {
      _trades = Collections.emptySet();
    } else {
      final Set<TradeInfo> tradeInfos = Sets.newHashSetWithExpectedSize(trades.size());
      for (Trade trade : trades) {
        tradeInfos.add(new TradeInfo(context, trade));
      }
      _trades = Collections.unmodifiableSet(tradeInfos);
    }
    _attributes = context.isIgnorePositionAttributes() ? Collections.<String, String>emptyMap() : position.getAttributes();
  }

  public Set<TradeInfo> getTrades() {
    return _trades;
  }

  public Map<String, String> getAttributes() {
    return _attributes;
  }

  @Override
  public String toString() {
    return "PositionInfo[quantity=" + getQuantity() + ", security=" + getSecurity() + ", trades=" + getTrades() + ", attributes=" + getAttributes() + "]";
  }

  @Override
  public boolean equals(final Object o) {
    if (o == this) {
      return true;
    }
    if (!(o instanceof PositionInfo)) {
      return false;
    }
    final PositionInfo other = (PositionInfo) o;
    if (!equalsImpl(other)) {
      return false;
    }
    return getTrades().equals(other.getTrades())
        && getAttributes().equals(other.getAttributes());
  }

  @Override
  public int hashCode() {
    int hc = hashCodeImpl();
    hc += (hc << 4) + getTrades().hashCode();
    hc += (hc << 4) + getAttributes().hashCode();
    return hc;
  }

}


text:
package chandu0101.scalajs.react.components.demo.routes

import chandu0101.scalajs.react.components.demo.components.reactpopover.ReactPopoverInfo
import chandu0101.scalajs.react.components.demo.components.reacttable.{ReactTableBasic, ReactTableCustomCell, ReactTableSorting}
import chandu0101.scalajs.react.components.demo.pages.{ReactJSDraggablePage, ReactTablePage}
import japgolly.scalajs.react.extra.router2.RouterConfigDsl

object ReactJSDraggableRouteModule {

  case object Info extends LeftRoute("Info", "info", () => ReactPopoverInfo())

  case object Demo extends LeftRoute("Demo", "demo", () => ReactTableBasic())

  val menu : List[LeftRoute] = List(Info,Demo)

  val routes = RouterConfigDsl[LeftRoute].buildRule { dsl =>

    import dsl._

    menu.map(i =>
      staticRoute(i.route, i) ~> renderR(r => ReactJSDraggablePage(i, r))
    ).reduce(_ | _)

  }
}


text:
<?php

declare(strict_types=1);

namespace Yansongda\Pay\Plugin\Wechat\Pay\Jsapi;

/**
 * @see https://pay.weixin.qq.com/wiki/doc/apiv3/apis/chapter3_1_8.shtml
 */
class DownloadBillPlugin extends \Yansongda\Pay\Plugin\Wechat\Pay\Common\DownloadBillPlugin
{
}


text:
SpongeVanilla [![Build Status](https://travis-ci.org/SpongePowered/SpongeVanilla.svg?branch=master)](https://travis-ci.org/SpongePowered/SpongeVanilla)
=============

**Currently not stable and under heavy development!**

SpongeVanilla is the SpongeAPI implementation for Vanilla Minecraft.

* [Homepage]
* [Source]
* [Issues]
* [Documentation]
* [Community Chat]: #sponge on irc.esper.net
* [Development Chat]: #spongedev on irc.esper.net

## Prerequisites
* [Java] 6

## Cloning
The following steps will ensure your project is cloned properly.

1. `git clone --recursive https://github.com/SpongePowered/SpongeVanilla.git`
2. `cd SpongeVanilla`
3. `cp scripts/pre-commit .git/hooks`

## Setup
__Note:__ If you do not have [Gradle] installed then use `./gradlew` for Unix systems or Git Bash and `gradlew.bat` for Windows systems in place of any `gradle` command.

Before you are able to build SpongeVanilla, you must first prepare the environment:

  - Run `gradle setupDecompWorkspace --refresh-dependencies`

**Note**: You may substitute `setupDecompWorkspace` for `setupCIWorkspace` when building on a CI such as [Jenkins].

### IDE Setup
__For [Eclipse]__
  1. Run `gradle eclipse`
  2. Import SpongeVanilla as an existing project (File > Import > General)
  3. Select the root folder for SpongeVanilla and make sure `Search for nested projects` is enabled
  4. Check SpongeVanilla when it finishes building and click **Finish**

__For [IntelliJ]__
  1. Make sure you have the Gradle plugin enabled (File > Settings > Plugins).
  2. Click File > New > Project from Existing Sources > Gradle and select the root folder for SpongeVanilla.

## Running
__Note:__ The following is aimed to help you setup run configurations for Eclipse and IntelliJ, if you do not want to be able to run SpongeVanilla directly from your IDE then you can skip this.

__For [Eclipse]__
  1. Go to **Run > Run Configurations**.
  2. Right-click **Java Application** and select **New**.
  3. Set the current project.
  4. Set the name as `Sponge (vanilla/server)` and apply the information for Server below.
  5. When launching the server for the first time, it will shutdown by itself. You will need to modify eula.txt to set eula=true (this means you agree to the Mojang EULA, if you do not wish to do this then you cannot run the server).

__For [IntelliJ]__
  1. Go to **Run > Edit Configurations**.
  2. Click the green + button and select **Application**.
  3. Set the name as `Sponge (vanilla/server)` and apply the information for Server below.
  4. When launching the server for the first time, it will shutdown by itself. You will need to modify eula.txt to set eula=true (this means you agree to the Mojang EULA, if you do not wish to do this then you cannot run the server).

__Server__

|     Property      | Value                         |
|:-----------------:|:------------------------------|
|    Main class     | GradleStartServer             |
| Program arguments | --noCoreSearch                |
| Working directory | ./run (Included in project)   |
| Module classpath  | SpongeVanilla (IntelliJ Only) |

## Building
__Note:__ If you do not have [Gradle] installed then use ./gradlew for Unix systems or Git Bash and gradlew.bat for Windows systems in place of any 'gradle' command.

__Note:__ You must [Setup the environment](#setup) before you can build SpongeVanilla.

In order to build SpongeVanilla you simply need to run the `gradle` command. You can find the compiled JAR files in `./build/libs` but in most cases
you'll only need 'spongevanilla-x.x.x-x.x-x.jar'.

## Updating your Clone
The following steps will update your clone with the official repo.

1. `git remote add upstream git@github.com:SpongePowered/SpongeVanilla.git`
2. `git pull --rebase upstream master`
3. `git submodule update --recursive`

## FAQ
__A dependency was added, but my IDE is missing it! How do I add it?__
>If a new dependency was added, you can just restart your IDE and the Gradle plugin for that IDE should pull in the new dependencies.

## Contributing
Are you a talented programmer looking to contribute some code? We'd love the help!
* Open a pull request with your changes, following our [guidelines](CONTRIBUTING.md).
* Please follow the above guidelines for your pull request(s) to be accepted.

__Help! Things are not working!__
>Some issues can be resolved by deleting the '.gradle' folder in your user directory and running through the setup steps again, or even running `gradle cleanCache` and running through the setup again. Otherwise if you are having trouble with something that the README does not cover, feel free to join our IRC channel and ask for assistance.

[Eclipse]: https://eclipse.org/
[Gradle]: https://gradle.org/
[Homepage]: https://spongepowered.org/
[IntelliJ]: http://www.jetbrains.com/idea/
[Issues]: https://github.com/SpongePowered/SpongeVanilla/issues
[Documentation]: https://docs.spongepowered.org/
[Java]: http://java.oracle.com/
[Source]: https://github.com/SpongePowered/SpongeVanilla/
[MIT License]: http://www.tldrlegal.com/license/mit-license
[Community Chat]: https://webchat.esper.net/?channels=sponge
[Development Chat]: https://webchat.esper.net/?channels=spongedev
[Jenkins]: https://jenkins-ci.org/


text:
package gosnmp

import (
	"fmt"
	"strings"
)

func (x *GoSNMP) walk(getRequestType PDUType, rootOid string, walkFn WalkFunc) error {
	if rootOid == "" || rootOid == "." {
		rootOid = baseOid
	}

	if !strings.HasPrefix(rootOid, ".") {
		rootOid = string(".") + rootOid
	}

	oid := rootOid
	requests := 0
	maxReps := x.MaxRepetitions
	if maxReps <= 0 {
		maxReps = defaultMaxRepetitions
	}

	getFn := func(oid string) (result *SnmpPacket, err error) {
		switch getRequestType {
		case GetBulkRequest:
			return x.GetBulk([]string{oid}, uint8(x.NonRepeaters), uint8(maxReps))
		case GetNextRequest:
			return x.GetNext([]string{oid})
		default:
			return nil, fmt.Errorf("Unsupported request type: %d", getRequestType)
		}
	}

RequestLoop:
	for {

		requests++
		response, err := getFn(oid)
		if err != nil {
			return err
		}
		if len(response.Variables) == 0 {
			break RequestLoop
		}

		for _, v := range response.Variables {
			if v.Type == EndOfMibView || v.Type == NoSuchObject || v.Type == NoSuchInstance {
				x.Logger.Printf("BulkWalk terminated with type 0x%x", v.Type)
				break RequestLoop
			}
			if !strings.HasPrefix(v.Name, rootOid) {
				// Not in the requested root range.
				break RequestLoop
			}
			if v.Name == oid {
				return fmt.Errorf("OID not increasing: %s", v.Name)
			}
			// Report our pdu
			if err := walkFn(v); err != nil {
				return err
			}
		}
		// Save last oid for next request
		oid = response.Variables[len(response.Variables)-1].Name
	}
	x.Logger.Printf("BulkWalk completed in %d requests", requests)
	return nil
}

func (x *GoSNMP) walkAll(getRequestType PDUType, rootOid string) (results []SnmpPDU, err error) {
	err = x.walk(getRequestType, rootOid, func(dataUnit SnmpPDU) error {
		results = append(results, dataUnit)
		return nil
	})
	return results, err
}


text:
// ----------------------------------------------------------------------------
// <copyright company="EFC" file ="SubscriptionBase.cs">
// All rights reserved Copyright 2015  Enterprise Foundation Classes
//
// </copyright>
//  <summary>
//  The <see cref="SubscriptionBase.cs"/> file.
//  </summary>
//  ---------------------------------------------------------------------------------------------
namespace EFC.Components.Events
{
    using System;
    using System.ComponentModel;
    using System.Reflection;
    using System.Windows.Threading;

    using EFC.Components.Exception;
    using EFC.Components.Validations;

    /// <summary>
    /// Represents a suscription that can be used to call an event handler on the subscriber.
    /// </summary>
    internal abstract class SubscriptionBase
    {
        /// <summary>
        /// The type of the event arguments.
        /// </summary>
        protected readonly Type handlerEventArgsType;

        /// <summary>
        /// The UI thread dispatcher.
        /// </summary>
        private readonly Dispatcher dispatcher;

        /// <summary>
        /// Initializes a new instance of the <see cref="SubscriptionBase"/> class.
        /// </summary>
        /// <param name="handlerMethodInfo">The handler method info.</param>
        /// <param name="dispatcher">The UI thread dispatcher.</param>
        /// <param name="threadOption">The thread option.</param>
        protected SubscriptionBase(MethodInfo handlerMethodInfo, Dispatcher dispatcher, ThreadOption threadOption)
        {
            Requires.NotNull(handlerMethodInfo, "handlerMethodInfo");
            if (!handlerMethodInfo.IsEventHandler())
            {
                throw ExceptionBuilder.ArgumentNotValid("handlerMethodInfo", Messages.InvalidEventHandlerParameters);
            }

            this.ThreadOption = threadOption;
            ParameterInfo paramInfo = handlerMethodInfo.GetParameters()[1];
            Type paramType = paramInfo.ParameterType;
            this.handlerEventArgsType = paramType;

            this.dispatcher = dispatcher;
        }

        /// <summary>
        /// Calls the specified publication.
        /// </summary>
        /// <param name="publication">The publication.</param>
        /// <param name="sender">The sender.</param>
        /// <param name="args">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        public virtual void Call(Publication publication, object sender, EventArgs args)
        {
            var eventParameeter = new[] { sender, args };
            Type publisherEventArgsType = args.GetType();
            if (!this.handlerEventArgsType.IsAssignableFrom(publisherEventArgsType))
            {
                throw new ArgumentException(string.Format(Messages.EventArgsAreNotAssignable, publisherEventArgsType, this.handlerEventArgsType));
            }
            switch (this.ThreadOption)
            {
                case ThreadOption.Publisher:
                    this.CallOnPublisher(eventParameeter);
                    break;
                case ThreadOption.Background:
                    this.CallOnBackgroundWorker(eventParameeter);
                    break;
                case ThreadOption.UserInterface:
                    this.CallOnUserInterface(eventParameeter);
                    break;
                default:
                    break;
            }
        }

        /// <summary>
        /// Gets the name of the handler method.
        /// </summary>
        /// <value>The name of the handler method.</value>
        public abstract string HandlerMethodName { get; }

        /// <summary>
        /// Gets the subscriber.
        /// </summary>
        /// <value>The subscriber.</value>
        public abstract object Subscriber { get; }

        /// <summary>
        /// Gets or sets the thread option.
        /// </summary>
        /// <value>The thread option.</value>
        public ThreadOption ThreadOption
        {
            get;
            private set;
        }

        /// <summary>
        /// Calls the publication on the publishers thread.
        /// </summary>
        /// <param name="parameters">The parameters.</param>
        private void CallOnPublisher(object[] parameters)
        {
            Delegate delegateAction = this.GetSubscriptionDelegate();
            if (delegateAction != null)
            {
                delegateAction.DynamicInvoke(parameters);
            }
        }

        /// <summary>
        /// Calls the publication on new background thread.
        /// </summary>
        /// <param name="parameters">The parameters.</param>
        private void CallOnBackgroundWorker(object[] parameters)
        {
            Delegate delegateAction = this.GetSubscriptionDelegate();
            if (delegateAction != null)
            {
                BackgroundWorker worker = new BackgroundWorker();
                worker.DoWork += (sender, e) => delegateAction.DynamicInvoke(parameters);

                worker.RunWorkerAsync();
            }
        }

        /// <summary>
        /// Calls the publication on the UI thread.
        /// </summary>
        /// <param name="parameters">The parameters.</param>
        private void CallOnUserInterface(object[] parameters)
        {
            Delegate delegateAction = this.GetSubscriptionDelegate();
            if (delegateAction != null)
            {
                this.dispatcher.BeginInvoke(DispatcherPriority.Normal, delegateAction, parameters);
            }
        }

        /// <summary>
        /// Gets the subscription delegate.
        /// </summary>
        /// <returns>The subscription delegate.</returns>
        protected abstract Delegate GetSubscriptionDelegate();

        /// <summary>
        /// Checks the handler action.
        /// </summary>
        /// <param name="handlerAction">The handler action.</param>
        /// <returns>The valid handler action.</returns>
        protected static Delegate CheckHandlerAction(Delegate handlerAction)
        {
            Requires.NotNull(handlerAction, "handlerAction");
            return handlerAction;
        }

        /// <summary>
        /// Matcheses the specified handler action.
        /// </summary>
        /// <param name="handlerAction">The handler action.</param>
        /// <returns><c>True</c> if the delegate is matching the subscription; otherwise false.</returns>
        public abstract bool Matches(Delegate handlerAction);

        /// <summary>
        /// Matcheses the specified subscriber.
        /// </summary>
        /// <param name="subscriber">The subscriber.</param>
        /// <param name="methodName">Name of the method.</param>
        /// <returns><c>True</c> if the subscriber method is matching the subscription; otherwise false.</returns>
        public abstract bool Matches(object subscriber, string methodName);
    }
}


text:
import anyTest, {TestInterface} from 'ava';

import {concat} from '.';

const test = anyTest as TestInterface<{sort: (a: string, b: string) => number}>;

test.beforeEach(t => {
	t.context = {
		sort: (a: string, b: string) => a.localeCompare(b)
	};
});

test('concat', t => {
	t.is(concat(['b', 'c', 'a'].sort(t.context.sort)), 'a b c');
});


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout_root"
    android:layout_width="200dp"
    android:layout_height="250dp"
    android:background="#ccc">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="一个自定义的Dialog" />
</LinearLayout>


text:
class CreateScores < ActiveRecord::Migration
  def change
    create_table :scores do |t|
      t.integer :score

      t.timestamps
    end
  end
end


text:
<?php

namespace ommu\ipedia\models\query;

class IpediaCompanies extends \yii\db\ActiveQuery
{
	/*
	public function active()
	{
		return $this->andWhere('[[status]]=1');
	}
	*/

	/**
	 * {@inheritdoc}
	 */
	public function published()
	{
		return $this->andWhere(['t.publish' => 1]);
	}

	/**
	 * {@inheritdoc}
	 */
	public function unpublish()
	{
		return $this->andWhere(['t.publish' => 0]);
	}

	/**
	 * {@inheritdoc}
	 */
	public function deleted()
	{
		return $this->andWhere(['t.publish' => 2]);
	}

	/**
	 * {@inheritdoc}
	 * @return \ommu\ipedia\models\IpediaCompanies[]|array
	 */
	public function all($db = null)
	{
		return parent::all($db);
	}

	/**
	 * {@inheritdoc}
	 * @return \ommu\ipedia\models\IpediaCompanies|array|null
	 */
	public function one($db = null)
	{
		return parent::one($db);
	}
}


text:
classdef ModulePartialLineBuffer < matlab.System  & ...
        matlab.system.mixin.Nondirect & ...
        matlab.system.mixin.CustomIcon %#codegen
    %MODULEPARTIALLINEBUFFER Partial line buffer module
    %
    % SVN identifier:
    % $Id: ModulePartialLineBuffer.m 683 2015-05-29 08:22:13Z sho $
    %
    % Requirements: MATLAB R2015b
    %
    % Copyright (c) 2014-2015, Shogo MURAMATSU
    %
    % All rights reserved.
    %
    % Contact address: Shogo MURAMATSU,
    %                Faculty of Engineering, Niigata University,
    %                8050 2-no-cho Ikarashi, Nishi-ku,
    %                Niigata, 950-2181, JAPAN
    %
    % http://msiplab.eng.niigata-u.ac.jp/
    %

    properties (Nontunable, PositiveInteger)
        LineLength = 1;
        StartIndexOfDelayChannel = 3;
        NumberOfDelayChannels = 2;
        NumberOfSymmetricChannels = 2;
        NumberOfAntisymmetricChannels = 2;
    end

    properties (Access=private)
        previousCd;
        currentIndex;
    end

    properties (DiscreteState)
    end

    methods
        function obj = ModulePartialLineBuffer(varargin)
            % Support name-value pair arguments
            setProperties(obj,nargin,varargin{:});
        end
    end

    methods (Access=protected)
        function setupImpl(obj, ~, ~)
            obj.previousCd = zeros(obj.NumberOfDelayChannels,obj.LineLength);
            obj.currentIndex = 1;
        end

        function resetImpl(obj)
            obj.currentIndex = 1;
        end

        function [cs, ca] = outputImpl(obj, cs, ca)
            coefs = [ cs; ca ];
            coefs(obj.StartIndexOfDelayChannel:obj.StartIndexOfDelayChannel+obj.NumberOfDelayChannels-1) = ...
                obj.previousCd(:,obj.currentIndex);
            cs = coefs(1:obj.NumberOfSymmetricChannels);
            ca = coefs(obj.NumberOfSymmetricChannels+1:obj.NumberOfSymmetricChannels+obj.NumberOfAntisymmetricChannels);
        end

        function updateImpl(obj, cs, ca)
            coefs = [ cs; ca ];
            obj.previousCd(:,obj.currentIndex) = ...
                coefs(obj.StartIndexOfDelayChannel:obj.StartIndexOfDelayChannel+obj.NumberOfDelayChannels-1);
            obj.currentIndex = mod(obj.currentIndex,obj.LineLength)+1;
        end

        function N = getNumInputsImpl(~)
            % Specify number of System inputs
            N = 2;
        end

        function [n1,n2] = getInputNamesImpl(~)
            n1 = 'Cs';
            n2 = 'Ca';
        end

        function N = getNumOutputsImpl(~)
            % Specify number of System outputs
            N = 2;
        end

        function [n1,n2] = getOutputNamesImpl(~)
            n1 = 'Cs';
            n2 = 'Ca';
        end

        function icon = getIconImpl(~)
            coder.extrinsic('sprintf')
            icon = sprintf('Partial\nLine Buf.');
        end
    end
end


text:
#import "EmulatorController.h"

#import <UIKit/UIScreen.h>

#ifdef IOS3
UIKIT_EXTERN_CLASS @interface UIScreenMode : NSObject {
  @private
    id _mode;
}

@property(readonly,nonatomic) CGSize  size;             // The width and height in pixels
@property(readonly,nonatomic) CGFloat pixelAspectRatio; // The aspect ratio of a single pixel. The ratio is defined as X/Y.

@end
#endif

@interface Bootstrapper : UIApplication  {

	UIWindow		    *deviceWindow;
	UIWindow            *externalWindow;
	NSArray             *screenModes;
	UIScreen            *externalScreen;
	EmulatorController	*hrViewController;
}

@end


text:
var moment = require('moment');
var _ = require('lodash');
var uuid = require('uuid');

/**
 * Initiate AWS DynamoDB bucket event.
 * @param {Object} options - Passed config options.
 * @param {Object} options.schema - DynamoDB table schema.
 * @param {string} options.region - Region of AWS S3 bucket.
 * @param {string} options.eventType - Event type that was defined in AWS S3 bucket
                                       (Put, Post, Copy, CompleteMultiPartUpload, Delete, DeleteMarkerCreated).
 * @param {string} options.eventName - Event name.
 * @param {string} options.functionName - Name of invoked function.
 */
function initAWSDynamoDB(options) {
  var self = this;
  var _opt = _.assignIn(this._options, options); // TODO: Get rid of Lodash.
  var invokeID = uuid.v1();
  var keys;

  try {
    keys = getKeys()
  } catch (err) {
    self.invoke = function() { throw new Error('Provide schema for current DynamoDB table.') };
    return self;
  }

  this.event = {
    Records: [{
      eventID: uuid.v4(),
      eventName: _opt.eventType,
      eventVersion: '1.0',
      eventSource: 'aws:dynamodb',
      awsRegion: _opt.region,
      dynamodb: {
        Keys: keys,
        NewImage: getImage(),
        StreamViewType: 'NEW_AND_OLD_IMAGES' // TODO: ViewType option.
      },
      eventSourceARN: 'test'
    }]
  };

  this.context = {
    awsRequestId: invokeID, // TODO: Investigate what the difference with invokeid.
    invokeid: invokeID,
    logGroupName: '/aws/lambda/' + _opt.functionName,
    functionName: _opt.functionName,
    memoryLimitInMB: _opt.memoryLimitInMB, // TODO: Investigate how to define used memory with invocation.
    functionVersion: '$LATEST', // TODO: Investigate how to recognize function versions.
    invokedFunctionArn: _opt.invokedFunctionArn,
    getRemainingTimeInMillis: function() { // TODO: Investigate how to return remaining time.
      return self.startAt - self.endAt;
    },
    succeed: function(data) {
      self.endAt = new Date().getTime();
      self.succeedCallCount++;
      self.invocationResult = data;
      return data;
    },
    fail: function(error) { // TODO: Substring error message[1].
      self.endAt = new Date().getTime();
      self.failCallCount++;
      self.invocationResult = { error: error };
      return error;
    },
    done: function(error, data) {} // TODO: Handle error and data.
  };

  /**
   * Get primary key for current schema
   * TODO: Investigate the posibility of adding more than 1 primary key.
   */
  function getKeys() {
    var keyObj = {};
    var keyType = {};

    // TODO: Implement unified parser for schema types.
    switch (options.schema[options.schema.primaryKey].toLowerCase()) {
      case 'string':
        keyType.S = options.item[options.schema.primaryKey];
        break;
      case 'number':
        keyType.N = options.item[options.schema.primaryKey];
        break;
      case 'binary':
        keyType.B = options.item[options.schema.primaryKey];
        break;
      default:
        keyType.S = options.item[options.schema.primaryKey];
    }

    keyObj[options.schema.primaryKey] = keyType;

    return keyObj;
  }

  function getImage() {
    var imageObj = {};

    for (var key in options.item) {
      var type = {};

      // TODO: Implement unified parser for schema types.
      switch (options.schema[key].toLowerCase()) {
        case 'string':
          type.S = options.item[key];
          break;
        case 'number':
          type.N = options.item[key];
          break;
        case 'binary':
          type.B = options.item[key];
          break;
        default:
          type.S = options.item[key];
      }

      imageObj[key] = type;
    }

    return imageObj;
  }
}

/** [1]
 * Note
 * For the error from context.fail(error) and context.done(error, null),
 * Lambda will log the first 256 KB of the error object. AWS Lambda will
 * truncate larger error objects when it logs the error, you will see
 * the text "- Truncated by Lambda" next to their error object.
 */

// TODO: Investigate the most appropriate options (+ add unique identificator for default options).
initAWSDynamoDB.prototype._options = {
  region: 'us-west-1',
  eventType: 'INSERT',
  functionName: 'test-lambda',
  memoryLimitInMB: '128',
  invokedFunctionArn: 'arn:aws:lambda:us-west-1:*:function:test-lambda'
};

// TODO: Implement function handler
initAWSDynamoDB.prototype.invoke = function(fn) {
  this.startAt = new Date().getTime();
  return fn(this.event, this.context);
};

/** Invocation result. By default - 'Process exited before completing request.' */
initAWSDynamoDB.prototype.invocationResult = 'Process exited before completing request.';

/** Context handlers counters */
initAWSDynamoDB.prototype.succeedCallCount = 0;
initAWSDynamoDB.prototype.failCallCount = 0;
initAWSDynamoDB.prototype.doneCallCount = 0;

/** Function time execution */
initAWSDynamoDB.prototype.startAt = 0;
initAWSDynamoDB.prototype.endAt = 0;

module.exports = initAWSDynamoDB;