text:
package de.estadata.mining.stclustering;

import de.estadata.mining.datatransformation.Cluster;
import de.estadata.mining.datatransformation.Report;
import de.estadata.mining.graphmodel.*;
import de.estadata.mining.util.DirectMemoryUtils;
import de.estadata.mining.util.MiningTools;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import net.sf.ehcache.config.CacheConfiguration;
import net.sf.ehcache.config.PersistenceConfiguration;
import net.sf.ehcache.config.SearchAttribute;
import net.sf.ehcache.config.Searchable;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

/**
 * This class is the core of the analysis. It provides the implementation for generating a {@link Graph} instance out of a set
 * of {@link Report} instances, as well as loading a previously existent Graph. This graph is generated accordingly to the
 * workbench defined in [Improving Participatory Urban Infrastructure Monitoring through Spatio-Temporal Analytics, by Borges et al].
 * We refer to it for the readers interested in the theoretical background.
 *
 * @author Nicolas Loza (nico.loza@gmail.com)
 *
 */
public class STFiltering {
	public static final String reportIDColumn = "id";
//	public static final String clusterIDLabel = "clusterID";
	private int maxSpaceDist;
	private int maxDayDist;
	private Graph graph;
	private long reportsStartTime;
	private long reportsEndTime;
	private long reportsTimeSpan;
	private CacheManager databaseManager;
	private Cache reportsCache;
	private Cache clustersCache;
//	private Cache[] bucketCaches;
	private Map<Integer, List<Integer>> buckets;
	private long initialFreeHeap = 0;
	private long initialDirectMemory = 0;
	private long reportsCacheHeap = 0;
	private long nodesHeap = 0;
	private long edgesHeap = 0;
	private long reportsCacheRAM = 0;
	private long nodesRAM = 0;
	private long edgesRAM = 0;

	/**
	 * Constructs a new instance from a specific set of {@link Report}s, defined by a list containing their IDs.
	 * @param reportIDs the list of IDs from the reports to be analyzed.
	 * @param databaseManager the Terracotta CacheManager
	 * @param reportsCache the Terracotta Cache containing the reports.
	 * @param maxSpaceDist maximal space distance (in meters) two Reports may have to be ST-connected.
	 * @param maxDayDist maximal temporal distance (in days) two Reports may have to be ST-connected.
	 * @throws InterruptedException
	 * @throws ExecutionException
	 */
	public STFiltering(List<Integer> reportIDs, CacheManager databaseManager,
			Cache reportsCache, int maxSpaceDist, int maxDayDist)
			throws InterruptedException, ExecutionException {
		initializeVariables(databaseManager, reportsCache, false);
		this.maxSpaceDist = maxSpaceDist;
		this.maxDayDist = maxDayDist;
		loadFromReportIDs(reportIDs);
		generateGraph();
	}

	/**
	 * Constructs a new instance using the complete set of {@link Report}s provided in a given Terracotta cache.
	 * @param databaseManager the Terracotta CacheManager.
	 * @param reportsCache the Terracotta Cache containing the reports.
	 * @param maxSpaceDist maximal space distance (in meters) two Reports may have to be ST-connected.
	 * @param maxDayDist maximal temporal distance (in days) two Reports may have to be ST-connected.
	 * @throws InterruptedException
	 * @throws ExecutionException
	 */
	public STFiltering(CacheManager databaseManager, Cache reportsCache,
			int maxSpaceDist, int maxDayDist) throws InterruptedException,
			ExecutionException {
		initializeVariables(databaseManager, reportsCache, false);
		this.maxSpaceDist = maxSpaceDist;
		this.maxDayDist = maxDayDist;
		loadFromReportIDs(null);
		generateGraph();

	}

	/**
	 * Constructs a new instance in one of two possible ways: by using a previously generated Graph structure or by
	 * generating a new graph using all available {@link Report}s in the given Terracotta and using default values
	 * for the maximal space and temporal distance (100m and 30 days, respectively). Note that, in the case of using a previously
	 * generated graph structure, the provided CacheManager should contain it in the form of two Caches with names
	 * '[reportsCache.name]_nodesCache' and '[reportsCache.name]_edgesCache'. These are the names used every time a new graph
	 * is generated, and therefore the program assumes that they are still there when attempting to re-load the graph on a later
	 * occasion.
	 * @param databaseManager the Terracotta CacheManager.
	 * @param reportsCache the Terracotta Cache containing the reports.
	 * @param useExistingGraphStructure if set to true, load previously generated {@link Graph}, if set to false, generate a new one.
	 * @throws InterruptedException
	 * @throws ExecutionException
	 */
	public STFiltering(CacheManager databaseManager, Cache reportsCache,
			boolean useExistingGraphStructure) throws InterruptedException,
			ExecutionException {
		initializeVariables(databaseManager, reportsCache,
				useExistingGraphStructure);
		if (useExistingGraphStructure) {
			checkForConsistency();
		} else {
			loadFromReportIDs(null);
			generateGraph();
		}
	}

	/**
	 * Execute the ST-filtering step using the maxSpace and maxTime values,
	 * which were either set in one of the constructors or the defaults were
	 * used. This method only changes the intern structure of the graph (i.e.
	 * only new edges appear, but the number of nodes remain the same). The
	 * reports stored in the database are not affected by the execution of this
	 * method.
	 *
	 * @throws ExecutionException
	 * @throws InterruptedException
	 */
	private void generateGraph() throws InterruptedException,
			ExecutionException {
		System.out.println("Starting to generate graph...");
		long start = System.currentTimeMillis();
		computeNeighbors();
		long end = System.currentTimeMillis();
		System.out.println("Finished generating graph with "
				+ graph.getNodeCount() + " nodes and " + graph.getEdgeCount()
				+ " edges after " + (end - start) + " ms");
		cleanupBuckets();
	}

	/**
	 * Filter graph with stricter constraints. Returns a {@link GraphView} containing the resulting nodes and edges after the filtering.
	 * @param newMaxSpaceDist new maximal spatial distance in meters. Must be in range [0,maxSpaceDist], where maxSpaceDist is the value set when constructing the object.
	 * @param newMaxDayDist new maximal temporal distance in days. Must be in range [0,maxDayDist], where maxDayDist is the value set when constructing the object.
	 * @param mustShareCategory if set to true, only edges connecting nodes of the same category are returned.
	 * @return a GraphView containg all nodes and edges remaining after the filtering.
	 * @throws InterruptedException
	 * @throws ExecutionException
	 */
	public GraphView filter(double newMaxSpaceDist, int newMaxDayDist,
			boolean mustShareCategory) throws InterruptedException,
			ExecutionException {
		if (newMaxSpaceDist < 0 || newMaxSpaceDist > this.maxSpaceDist)
			throw new IllegalArgumentException(
					"Invalid value for first argument. Must have a value between 0 and "
							+ this.maxSpaceDist);

		if (newMaxDayDist < 0 || newMaxDayDist > this.maxDayDist)
			throw new IllegalArgumentException(
					"Invalid value for second argument. Must have a value between 0 and "
							+ this.maxDayDist);

		System.out
				.println("Applying filtering to graph with new maxSpaceDist: "
						+ newMaxSpaceDist + " meters, new maxTempDist: "
						+ newMaxDayDist + " days and mustShareCategory: "
						+ mustShareCategory);
		long start = System.currentTimeMillis();

		GraphView view = new GraphView(graph);
		view.addAllNodeIDs(graph.getNodeIDs());

		for (int id : graph.getEdgeIDs()) {
			Edge e = graph.getEdge(id);
			if (mustShareCategory && !e.isSameCategory()) {
				continue;
			} else if (e.getSpaceDist() <= newMaxSpaceDist && e.getTimeDist() <= newMaxDayDist)
				view.addEdgeID(e.getID());
		}
		long end = System.currentTimeMillis();
		System.out.println("Filtering took: " + (end - start) + " ms");

		System.out.println("Original graph has " + graph.getNodeCount()
				+ " nodes and " + graph.getEdgeCount() + " edges");
		System.out.println("Filtered graph hast " + view.getNodeIDs().size()
				+ " nodes and " + view.getEdgeIDs().size() + " edges");

		return view;
	}

	/**
	 * Labels the nodes of every connected component with a single, unique,
	 * positive cluster ID, as long as said component consists of 2 or more
	 * nodes. Isolated nodes (i.e. nodes without any incident edges) are labeled
	 * with the cluster ID '-1'. The labeling of a node with a cluster ID is
	 * reflected in the corresponding report, which is stored in the main Cache.
	 * Reports with the same cluster ID are then gathered under a Cluster
	 * instance and stored in the cluster Cache.
	 *
	 * @param clustersCache
	 *            The cache where the Cluster instances are going to be stored.
	 */
	public void generateAndTransferClusters(Cache clustersCache) {
		generateAndTransferClusters(clustersCache, null);
	}

	/**
	 * Labels the nodes of every connected component (given by the {@link GraphView}) with a single, unique,
	 * positive cluster ID, as long as said component consists of 2 or more
	 * nodes. Isolated nodes (i.e. nodes without any incident edges) are labeled
	 * with the cluster ID '-1'. The labeling of a node with a cluster ID is
	 * reflected in the corresponding report, which is stored in the main Cache.
	 * Reports with the same cluster ID are then gathered under a Cluster
	 * instance and stored in the cluster Cache.
	 *
	 * @param clustersCache the cache where the Cluster instances are going to be stored.
	 * @param view the GraphView instance containing the sets of node and edge IDs to be taken into account.
	 */
	public void generateAndTransferClusters(Cache clustersCache, GraphView view) {
		long start = System.currentTimeMillis();
		MiningTools.assignClusterIDsOnGraph(graph, view);
		Map<Integer, List<Report>> clusterMap = new HashMap<Integer, List<Report>>();
		for (Integer id : graph.getNodeIDs()) {
			if (view == null || view.containsNodeID(id)) {
				Node n = graph.getNode(id);
				int clusterID = n.getClusterID();
				if(clusterID == Integer.MIN_VALUE)
					throw new IllegalStateException("Failed to assign a valid cluster ID to at least one node");
				Report report = (Report) reportsCache.get(id).getObjectValue();
				report.setClusterID(clusterID);
				reportsCache.put(new Element(id, report));
				MiningTools.addReportToClustermap(report, clusterMap);
			}
		}
		long time = System.currentTimeMillis() - start;
		System.out.println("Assignment of clusterIDs to nodes & reports took " + time + " ms");
		clustersCache.removeAll();
		for (Integer key : clusterMap.keySet()) {
			Cluster cluster = new Cluster(clusterMap.get(key), key);
			Element element = new Element(key, cluster);
			clustersCache.put(element);
		}
		this.clustersCache = clustersCache;
	}

	/**
	 * Exports graph and clusters to csv files.
	 * @param pointsDestFilePath destination file of the graph.
	 * @param clustersDestFilePath destination file of the clusters.
	 * @throws FileNotFoundException
	 * @throws UnsupportedEncodingException
	 */
	public void exportToCSV(String pointsDestFilePath,
			String clustersDestFilePath) throws FileNotFoundException,
			UnsupportedEncodingException {
		List<Report> reports = MiningTools.getCacheObjectsAsList(reportsCache,
				Report.class, null);
		List<Cluster> clusters = (clustersCache == null) ? null : MiningTools.getCacheObjectsAsList(clustersCache, Cluster.class, null);
		MiningTools.resultsToCSV(reports, pointsDestFilePath,
				clustersDestFilePath, clusters);
	}

	private void initializeVariables(CacheManager databaseManager,
			Cache reportsCache, boolean useExistingGraphStructure) {
		this.databaseManager = databaseManager;
		this.reportsCache = reportsCache;

		if (reportsCache == null)
			throw new NullPointerException();

		initialFreeHeap = getMaxAvailableHeapMemory();
		initialDirectMemory = DirectMemoryUtils.getDirectMemorySize();

		reportsCacheHeap = reportsCache.getCacheConfiguration()
				.getMaxBytesLocalHeap();
		reportsCacheRAM = reportsCache.getCacheConfiguration()
				.getMaxBytesLocalOffHeap();

		nodesHeap = (initialFreeHeap - reportsCacheHeap) / 4;
		edgesHeap = nodesHeap;

		nodesRAM = (initialDirectMemory - reportsCacheRAM) / 3;
		edgesRAM = nodesRAM;

		String nodesCacheName = reportsCache.getName() + "_nodesCache";
		String edgesCacheName = reportsCache.getName() + "_edgesCache";
		Cache nodesCache;
		Cache edgesCache;
		if (useExistingGraphStructure) {
			nodesCache = databaseManager.getCache(nodesCacheName);
			edgesCache = databaseManager.getCache(edgesCacheName);
			if (nodesCache == null || edgesCache == null) {
				throw new IllegalStateException(
						"Cannot continue: missing existing graph structure");
			}
		} else {
			Hashtable<String, String> nodeAttributes = new Hashtable<>();
			Hashtable<String, String> edgeAttributes = new Hashtable<>();

			nodeAttributes.put("id", "getID()");

			edgeAttributes.put("id", "getID()");
			edgeAttributes.put("sourceID", "getSourceID()");
			edgeAttributes.put("targetID", "getTargetID()");
			edgeAttributes.put("weight", "getWeight()");

			nodesCache = getNewCache(nodesCacheName, nodesHeap, nodesRAM, true, nodeAttributes);
			edgesCache = getNewCache(edgesCacheName, edgesHeap, edgesRAM, true, edgeAttributes);
		}

		graph = new Graph(nodesCache, edgesCache);

		maxSpaceDist = 100;
		maxDayDist = 30;
	}

	private void computeNeighbors() throws InterruptedException, ExecutionException {

		final int threads = Runtime.getRuntime().availableProcessors();
		ExecutorService pool = Executors.newFixedThreadPool(threads);
		List<Future<List<Edge>>> futures = new ArrayList<Future<List<Edge>>>();
		Integer[] keys = buckets.keySet().toArray(new Integer[buckets.size()]);

		for (int i = 0; i < keys.length; i++) {
			Future<List<Edge>> f = pool.submit(new BucketThread(keys[i]));
			futures.add(f);
		}
		for (int i = 0; i + 1 < keys.length; i += 2) {
			Future<List<Edge>> f = pool.submit(new BucketThread(keys[i], keys[i + 1]));
			futures.add(f);
		}
		for (int i = 1; i + 1 < keys.length; i += 2) {
			Future<List<Edge>> f = pool.submit(new BucketThread(keys[i], keys[i + 1]));
			futures.add(f);
		}

		try {
			for (Future<List<Edge>> f : futures) {
				List<Edge> edges = f.get();
				if (edges.size() == 0) {
				} else {
					for (Edge e : edges)
						graph.addEdge(e);
				}
			}
		} catch (InterruptedException e) {
			pool.shutdownNow();
			throw e;
		} catch (ExecutionException e) {
			pool.shutdownNow();
			throw e;
		}

		pool.shutdown();

	}

	/*
	 * ##########################################################################
	 * # Auxiliary class for version 3.1 Instances of this class are going to be
	 * later on called in parallel.
	 */
	private class BucketThread implements Callable<List<Edge>> {

		// Indices pointing to the corresponding buckets in the bucket array
		private int firstCacheIndex = -1;
		private int secondCacheIndex = -1;

		public BucketThread(int firstCacheIndex) {
			if (firstCacheIndex < 0)
				throw new IllegalArgumentException();
			this.firstCacheIndex = firstCacheIndex;
		}

		public BucketThread(int firstCacheIndex, int secondCacheIndex) {
			if (firstCacheIndex < 0 || secondCacheIndex < 0)
				throw new IllegalArgumentException();
			this.firstCacheIndex = firstCacheIndex;
			this.secondCacheIndex = secondCacheIndex;
		}

		public List<Edge> call() throws Exception {
			long start = System.currentTimeMillis();
			List<Edge> edges = new ArrayList<Edge>();

			List<Report> firstCacheReports = MiningTools.getCacheObjectsAsList(reportsCache, Report.class, buckets.get(firstCacheIndex));
			firstCacheReports = (firstCacheReports == null) ? new ArrayList<Report>() : firstCacheReports;
			String msg;
			if (secondCacheIndex == -1) {
				edges = processReportsLists(firstCacheReports,
						firstCacheReports, true);
				msg = "Processing of cache " + firstCacheIndex + " ("
						+ firstCacheReports.size() + " reports) took: ";
			} else {
				List<Report> secondCacheReports = MiningTools.getCacheObjectsAsList(reportsCache, Report.class, buckets.get(secondCacheIndex));
				secondCacheReports = (secondCacheReports == null) ? new ArrayList<Report>() : secondCacheReports;
				edges = processReportsLists(firstCacheReports,
						secondCacheReports, false);
				msg = "Processing of caches ["
						+ firstCacheIndex
						+ ", "
						+ secondCacheIndex
						+ "] ("
						+ (firstCacheReports.size() + secondCacheReports.size())
						+ " reports) took: ";
			}

			long end = System.currentTimeMillis();
			msg += (end - start) + " ms";
			System.out.println(msg);
			return edges;
		}

		private List<Edge> processReportsLists(List<Report> l1,
				List<Report> l2, boolean sameList) {
			List<Edge> edges = new ArrayList<Edge>();
			for (int i = 0; i < l1.size(); i++) {
				Report r1 = l1.get(i);
				int j = (sameList) ? i + 1 : 0;
				for (; j < l2.size(); j++) {
					Report r2 = l2.get(j);
					int spaceDist = Math.abs(MiningTools.getSpaceDistance(r1, r2));
					if (spaceDist < maxSpaceDist) {
						long maxTemporalDist = TimeUnit.DAYS.toMillis(maxDayDist);
						long timeDist = Math.abs(r1.getCreationTime() - r2.getCreationTime());
						if (timeDist < maxTemporalDist) {
							Node n1 = graph.getNode(r1.getID());
							Node n2 = graph.getNode(r2.getID());
							boolean sameCategory = r1.getCategory().toLowerCase().equals(r2.getCategory().toLowerCase());

							Edge e = new Edge(n1, n2, MiningTools.getLevenshteinSimilarity(r1.getCategory(), r2.getCategory()));

							e.setSpaceDist(spaceDist);
							e.setTimeDist((int) TimeUnit.MILLISECONDS.toDays(timeDist));
							e.setSameCategory(sameCategory);

							edges.add(e);
						}
					}
				}
			}
			return edges;
		}
	}

	private void loadFromReportIDs(List<Integer> reportIDs)
			throws InterruptedException, ExecutionException {
		System.out.println("Loading graph nodes...");
		long start = System.currentTimeMillis();

		reportsStartTime = Long.MAX_VALUE;
		reportsEndTime = Long.MIN_VALUE;
		final Object timeStampsLock = new Object();

		graph.clear();

		// ########################
		final Object[] keys = (reportIDs != null) ? reportIDs.toArray()
				: reportsCache.getKeys().toArray();

		int processors = Runtime.getRuntime().availableProcessors();
		ExecutorService pool = Executors.newFixedThreadPool(processors);
		List<Future<Integer>> futures = new ArrayList<>();

		int lowerBound = 0;
		int upperBound = 0;
		int step = keys.length / processors;
		for (int i = 0; i < processors; i++) {
			lowerBound = upperBound;
			upperBound = (i == processors - 1) ? keys.length
					: (upperBound + step);
			final int finalLowerBound = lowerBound;
			final int finalUpperBound = upperBound;
			Future<Integer> f = pool.submit(new Callable<Integer>() {
				@Override
				public Integer call() throws Exception {
					int count = 0;
					for (int j = finalLowerBound; j < finalUpperBound; j++) {
						Report r = (Report) reportsCache.get(keys[j]).getObjectValue();
						int id = r.getID();
						long creationTime = r.getCreationTime();
						Node n = new Node(id);
						if (!graph.addNode(n))
							throw new IllegalStateException(
									"Failed to insert node (ID was in use)");
						synchronized (timeStampsLock) {
							if (creationTime < reportsStartTime)
								reportsStartTime = creationTime;
							if (creationTime > reportsEndTime)
								reportsEndTime = creationTime;
						}
						count++;
					}
					return count;
				}
			});
			futures.add(f);
		}
		int totalFromThreads = 0;
		for (Future<Integer> f : futures) {
			totalFromThreads += f.get();
		}
		pool.shutdown();
		int keysSize = reportsCache.getKeys().size();
		if (totalFromThreads != keys.length
				|| totalFromThreads != graph.getNodeCount()
				|| totalFromThreads != keysSize) {
			throw new IllegalStateException("totalFromThreads: "
					+ totalFromThreads + ", keys: " + keys.length
					+ ", nodes: " + graph.getNodeCount() + ", reports: "
					+ keysSize);
		}
		// ########################
		long end = System.currentTimeMillis();
		System.out.println("Finished loading graph nodes after "
				+ (end - start) + "ms");
		// Compute number of buckets
		if (reportsEndTime < reportsStartTime
				&& (reportsEndTime != Long.MIN_VALUE && reportsStartTime != Long.MAX_VALUE))
			throw new IllegalStateException(
					"Ending time of the reports cannot be previous to the starting time.");

		reportsTimeSpan = reportsEndTime - reportsStartTime;
		long maxDayDistInMs = TimeUnit.DAYS.toMillis(maxDayDist);
		int monthsSpan = (reportsTimeSpan % maxDayDistInMs == 0) ? (int) (reportsTimeSpan / maxDayDistInMs)
				: (int) (reportsTimeSpan / maxDayDistInMs) + 1;
		buckets = new Hashtable<Integer, List<Integer>>(monthsSpan);
		System.out.println("#buckets = " + buckets.size());
		transferDataToDB(monthsSpan);
	}

	private void transferDataToDB(int span)
			throws InterruptedException, ExecutionException {
		System.out.println("Transfering nodes to buckets...");

		int processors = Runtime.getRuntime().availableProcessors();
		ExecutorService pool = Executors.newFixedThreadPool(processors);
		List<Future<Integer>> futures = new ArrayList<Future<Integer>>();

		final Object[] bucketLocks = new Object[span];
		for (int i = 0; i < bucketLocks.length; i++) {
			bucketLocks[i] = new Object();
		}

		// First: construct for each bucket a list of reportIDs from the reports
		// that correspond to said bucket.
		int lowerBound = 0;
		int upperBound = 0;
		final Object[] reportIDs = graph.getNodeIDs().toArray();
		int step = graph.getNodeCount() / processors;
		for (int i = 0; i < processors; i++) {
			lowerBound = upperBound;
			upperBound = (i == processors - 1) ? graph.getNodeCount()
					: (upperBound + step);
			final int finalLowerBound = lowerBound;
			final int finalUpperBound = upperBound;
			Future<Integer> f = pool.submit(new Callable<Integer>() {

				public Integer call() throws Exception {
					int count = 0;
					for (int j = finalLowerBound; j < finalUpperBound; j++) {
						Report rep = (Report) reportsCache.get(reportIDs[j]).getObjectValue();
						int bucketIndex = getBucketIndex(rep);
						synchronized (bucketLocks[bucketIndex]) {
							List<Integer> bucketReportIDs = buckets.get(bucketIndex);
							if (bucketReportIDs == null) {
								bucketReportIDs = new ArrayList<Integer>();
							}
							bucketReportIDs.add(rep.getID());
							buckets.put(bucketIndex, bucketReportIDs);
						}
						count++;
					}
					return count;
				}

				private int getBucketIndex(Report rep) {
					return (int) (Math.abs(rep.getCreationTime() - reportsStartTime) / TimeUnit.DAYS.toMillis(maxDayDist));
				}
			});
			futures.add(f);
		}

		int totalFromThreads = 0;
		for (Future<Integer> f : futures) {
			totalFromThreads += f.get();
		}

		int totalInBuckets = 0;
		for(Entry<Integer, List<Integer>> entry : buckets.entrySet()) {
			totalInBuckets += entry.getValue().size();
		}

		int totalKeys = reportsCache.getKeys().size();
		if (totalFromThreads != totalKeys
				|| totalFromThreads != graph.getNodeCount()
				|| totalInBuckets != totalKeys) {
			cleanupBuckets();
			throw new IllegalStateException("total: " + totalFromThreads
					+ ", nodes: " + graph.getNodeCount() + ", reports: " + totalKeys
					+ ", in buckets: " + totalInBuckets);
		}
	}

	private void cleanupBuckets() {
		buckets.clear();
	}

	private Cache getNewCache(String cacheName, long maxBytesLocalHeap,
			long maxBytesLocalOffHeap, boolean persistent, Hashtable<String, String> searchableAttributes) {
		if (databaseManager.cacheExists(cacheName)) {
			throw new IllegalArgumentException("Cache '" + cacheName
					+ "' already exists");
		}

		CacheConfiguration cacheConfig = new CacheConfiguration(cacheName, 0)
				.eternal(true);
		cacheConfig.setMaxBytesLocalHeap(maxBytesLocalHeap);

		// Overflow to OffHeap
		cacheConfig.overflowToOffHeap(true);
		if (maxBytesLocalOffHeap >= 1024 * 1024)
			cacheConfig.setMaxBytesLocalOffHeap(maxBytesLocalOffHeap);
		else
			cacheConfig.setMaxBytesLocalOffHeap("50M");

		// Overflow to Disk
		cacheConfig.setMaxEntriesLocalDisk(0);
		cacheConfig.persistence(new PersistenceConfiguration()
		.strategy(PersistenceConfiguration.Strategy.LOCALRESTARTABLE));
//		if(persistent){
//			cacheConfig.persistence(new PersistenceConfiguration()
//			.strategy(PersistenceConfiguration.Strategy.LOCALRESTARTABLE));
//		} else {
//			cacheConfig.persistence(new PersistenceConfiguration()
//			.strategy(PersistenceConfiguration.Strategy.LOCALTEMPSWAP));
//		}

		cacheConfig.setMemoryStoreEvictionPolicy("LRU");

		// Reference the object directly
		cacheConfig.setCopyOnRead(false);

		Searchable searchable = new Searchable();
		if(searchableAttributes != null) {
			for(Entry<String, String> entry : searchableAttributes.entrySet())
				searchable.addSearchAttribute(new SearchAttribute().name(entry.getKey()).expression("value." + entry.getValue()));
		}

		cacheConfig.addSearchable(searchable);

		Cache newCache = new Cache(cacheConfig);
		databaseManager.addCache(newCache);

		return newCache;
	}

	private long getMaxAvailableHeapMemory() {
		Runtime rt = Runtime.getRuntime();
		return rt.maxMemory() - (rt.totalMemory() - rt.freeMemory());
	}

	private void checkForConsistency() {
		for (Object key : reportsCache.getKeys()) {
			// Report r = (Report) reportsCache.get(key).getObjectValue();
			if (!graph.containsNodeID((int) key)) {
				throw new IllegalStateException(
						"Cache "
								+ reportsCache.getName()
								+ " is not consistent with the data stored in the current graph.");
			}
		}
	}

	/**
	 * Returns the current graph.
	 * @return the current graph.
	 */
	public Graph getGraph() {
		return graph;
	}

	/**
	 *
	 * @return Get the value of the maximum space distance (in meters) two
	 *         reports can be separated from one another in order to be
	 *         ST-Connected
	 */
	public double getMaxSpaceDist() {
		return maxSpaceDist;
	}

	/**
	 * @return Get the value of the maximum time distance (in milliseconds) two
	 *         reports can be separated from one another in order to be
	 *         ST-Connected.
	 */
	public long getMaxTimeDist() {
		return maxDayDist;
	}

	/**
	 * Returns the current maximal temporal distance in days.
	 * @return the current maximal temporal distance in days.
	 */
	public int getMaxDayDist() {
		return maxDayDist;
	}

	/**
	 * Sets a new value for the maximal spatial distance in meters.
	 * @param maxSpaceDist the new value for the maximal spatial distance in meters.
	 */
	public void setMaxSpaceDist(int maxSpaceDist) {
		this.maxSpaceDist = maxSpaceDist;
	}

	/**
	 * Sets a new value for the maximal temporal distance in days.
	 * @param maxDayDist the new value for the maximal temporal distance in days.
	 */
	public void setMaxDayDist(int maxDayDist) {
		this.maxDayDist = maxDayDist;
	}

	/**
	 * Returns the current CacheManager.
	 * @return the current CacheManager.
	 */
	public CacheManager getDatabaseManager() {
		return databaseManager;
	}

}


text:
package org.apache.flink.table.gateway.utils;

/**
 * A structure describes a SQL statement for testing.
 *
 * @see SqlScriptReader
 */
public class TestSqlStatement {
    private final String comment;
    private final String sql;

    public TestSqlStatement(String comment, String sql) {
        this.comment = comment;
        this.sql = sql;
    }

    public String getComment() {
        return comment;
    }

    public String getSql() {
        return sql;
    }
}

redpajama_set_name: RedPajamaGithub


text:
using FluentAssertions;
using NSubstitute;
using System;
using System.Reactive;
using System.Reactive.Linq;
using Toggl.Core.DataSources.Interfaces;
using Toggl.Core.Sync.States.Push;
using Toggl.Storage;
using Xunit;

namespace Toggl.Core.Tests.Sync.States.Push
{
    public sealed class DeleteLocalEntityStateTests
    {
        private readonly IDataSource<IThreadSafeTestModel, IDatabaseTestModel> dataSource
            = Substitute.For<IDataSource<IThreadSafeTestModel, IDatabaseTestModel>>();

        [Fact, LogIfTooSlow]
        public void ReturnsFailTransitionWhenEntityIsNull()
        {
            var state = new DeleteLocalEntityState<IDatabaseTestModel, IThreadSafeTestModel>(dataSource);

            var transition = state.Start(null).SingleAsync().Wait();

            transition.Result.Should().Be(state.DeletingFailed);
        }

        [Fact, LogIfTooSlow]
        public void ReturnsFailTransitionWhenDatabaseOperationFails()
        {
            var state = new DeleteLocalEntityState<IDatabaseTestModel, IThreadSafeTestModel>(dataSource);
            var entity = new TestModel(0, SyncStatus.SyncNeeded);
            dataSource.Delete(entity.Id).Returns(Observable.Throw<Unit>(new Exception()));

            var transition = state.Start(entity).SingleAsync().Wait();

            transition.Result.Should().Be(state.DeletingFailed);
        }

        [Fact, LogIfTooSlow]
        public void ReturnsDeletedTransitionWhenEverythingIsOk()
        {
            var state = new DeleteLocalEntityState<IDatabaseTestModel, IThreadSafeTestModel>(dataSource);
            var entity = new TestModel(0, SyncStatus.SyncNeeded);
            dataSource.Delete(Arg.Any<long>()).Returns(Observable.Return(Unit.Default));

            var transition = state.Start(entity).SingleAsync().Wait();

            transition.Result.Should().Be(state.Done);
        }

        [Fact, LogIfTooSlow]
        public void DeletesTheEntityFromTheLocalDatabase()
        {
            var state = new DeleteLocalEntityState<IDatabaseTestModel, IThreadSafeTestModel>(dataSource);
            var entity = new TestModel(0, SyncStatus.SyncNeeded);
            dataSource.Delete(Arg.Any<long>()).Returns(Observable.Return(Unit.Default));

            state.Start(entity).SingleAsync().Wait();

            dataSource.Received().Delete(Arg.Any<long>());
        }
    }
}


text:
require 'test_helper'
require 'generators/user_migration/user_migration_generator'

module SqrlOnRails
  class UserMigrationGeneratorTest < Rails::Generators::TestCase
    tests UserMigrationGenerator
    destination Rails.root.join('tmp/generators')
    setup :prepare_destination

    # test "generator runs without errors" do
    #   assert_nothing_raised do
    #     run_generator ["arguments"]
    #   end
    # end
  end
end


text:
package me.puras.common.cache;

/**
 * @author puras <he@puras.me>
 * @since 16/1/14  上午11:04
 */
public class CacheException extends RuntimeException {
    public CacheException() {
    }

    public CacheException(String message) {
        super(message);
    }

    public CacheException(String message, Throwable cause) {
        super(message, cause);
    }

    public CacheException(Throwable cause) {
        super(cause);
    }

    public CacheException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }
}


text:
@implementation XMPPMessageTimestampParser

+ (NSDate*)parseTimestampFromXmlElement:(id)xmlElement
{
    if (nil == xmlElement)
    {
        return nil;
    }

    NSParameterAssert([xmlElement isKindOfClass: [NSXMLElement class]]);
    NSXMLElement* selfElement = (NSXMLElement*)xmlElement;

    NSXMLElement* delayElement = [[selfElement elementsForName: @"delay"] firstObject];
    NSXMLElement* xElement = [[selfElement elementsForName: @"x"] firstObject];

    NSXMLElement* elementWithTimestamp = nil;
    NSString* timestampFormat = nil;
    if (nil != delayElement)
    {
        elementWithTimestamp = delayElement;
        timestampFormat = @"yyyy-MM-dd'T'HH:mm:ss.SSSSSSZ";
    }
    else
    {
        elementWithTimestamp = xElement;
        timestampFormat = @"yyyy-MM-dd'T'HH:mm:ss";
    }

    if (nil != elementWithTimestamp)
    {
        // TODO : cache NSDateFormatter object for performance
        NSLocale* posixLocale = [[NSLocale alloc] initWithLocaleIdentifier: @"en_US_POSIX"];
        NSCalendar* gregorianCal = [[NSCalendar alloc] initWithCalendarIdentifier: NSCalendarIdentifierGregorian];
        NSDateFormatter* df = [NSDateFormatter new];
        {
            gregorianCal.locale = posixLocale;
            df.locale = posixLocale;
            df.calendar = gregorianCal;
        }
        df.dateFormat = timestampFormat;

        NSString* strResult = [[elementWithTimestamp attributeForName: @"stamp"] stringValue];
        NSDate* result = [df dateFromString: strResult];

        return result;
    }

    return nil;
}

+ (NSString*)parseIdFromXmlMessage:(id)xmlElement
{
    NSXMLElement* castedMessage = (NSXMLElement*)xmlElement;
    if (nil == xmlElement)
    {
        return nil;
    }

    NSString* result = [self parseIdFromXmlElement: xmlElement];
    if (nil != result)
    {
        return result;
    }

    // recursive calls follow
    NSXMLElement* archivedElement = [[castedMessage elementsForName: @"archived"] firstObject];
    if (nil != archivedElement)
    {
        result = [self parseIdFromXmlMessage: archivedElement];
        return result;
    }

    NSXMLElement* resultElement = [[castedMessage elementsForName: @"result"] firstObject];
    if (nil != resultElement)
    {
        result = [self parseIdFromXmlMessage: resultElement];
        return result;
    }

    return nil;
}

+ (NSString*)parseIdFromXmlElement:(id)xmlElement
{
    NSXMLElement* castedMessage = (NSXMLElement*)xmlElement;
    NSXMLNode* idAttribute = [castedMessage attributeForName: @"id"];
    if (nil != idAttribute)
    {
        NSString* idValue = [idAttribute stringValue];
        return idValue;
    }

    return nil;
}

@end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Valsa sibirica Thüm.

### Remarks
null


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Agaricus campestris var. varius J. Drumm. ex Berk.

### Remarks
null


text:
Rhino Princess - 2012
========

Rhino Princess's code for the 2012 FRC competition, Rebound Rumble.


text:
package tianma.swing.example.layout;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTree;
import javax.swing.SwingUtilities;

/**
 * ÑÝʾFlowLayout(Á÷²¼¾Ö)
 *
 * @author Tianma
 *
 */
public class FlowLayoutSample extends JFrame {

	private static final long serialVersionUID = 1L;

	public FlowLayoutSample() {
		initUI();
	}

	private void initUI() {
		JPanel panel = new JPanel();// JPanelĬÈϵIJ¼¾Ö¹ÜÀíÆ÷ΪFlowLayout

		JTextArea area = new JTextArea("Text Area");
		// area.setPreferredSize(new Dimension(100, 100));

		JButton button = new JButton("Button");
		panel.add(button);

		JTree tree = new JTree();
		panel.add(tree);

		panel.add(area);

		add(panel);

		pack();

		setTitle("FlowLayout Sample");
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		setLocationRelativeTo(null);

	}

	public static void main(String[] args) {
		SwingUtilities.invokeLater(new Runnable() {

			@Override
			public void run() {
				FlowLayoutSample sample = new FlowLayoutSample();
				sample.setVisible(true);
			}
		});
	}

}


text:
using System.Collections.Generic;
using System.Web.Http;
using NewsMonitor.API.ConsoleHost.Models;
using NewsMonitor.API.ConsoleHost.Models.ArticleModel;

namespace NewsMonitor.API.ConsoleHost.Controllers
{
    [RoutePrefix("news-sources")]
    public class NewsSourcesController:ApiController
    {
        private readonly List<NewsSourceModel> _sources = new List<NewsSourceModel>
        {
            new NewsSourceModel {Name="first"},
            new NewsSourceModel {Name="second" }
        };

        [HttpGet]
        [Route("{name}/articles")]
        public List<ArticleModel> GetArticleFromCurrentNewsSource(string name)
        {
            List<ArticleModel> result=null;

            foreach (var source in _sources)
                if (source.Name == name)
                    result= new List<ArticleModel>
                    {
                        new ArticleModel {Text="Test" }
                    };

            return result;
        }
    }
}


text: export default class Example {}


text:
Track stats and display them in a web UI.

Stats To be Tracked and compared:
Data from Activity/Apple Watch and data from Fitbit

Coffee Stats!
When, where, what kind


text:
import textwrap, random, os, sys
from itertools import chain, islice, izip

class Chomsky:
    def __init__(self, times=1, line_length=os.popen('stty size', 'r').read().split()[1]):
        self.leadins = """To characterize a linguistic level L,
            On the other hand,
            This suggests that
            It appears that
            Furthermore,
            We will bring evidence in favor of the following thesis:
            To provide a constituent structure for T(Z,K),
            From C1, it follows that
            For any transformation which is sufficiently diversified in application to be of any interest,
            Analogously,
            Clearly,
            Note that
            Of course,
            Suppose, for instance, that
            Thus
            With this clarification,
            Conversely,
            We have already seen that
            By combining adjunctions and certain deformations,
            I suggested that these results would follow from the assumption that
            If the position of the trace in (99c) were only relatively inaccessible to movement,
            However, this assumption is not correct, since
            Comparing these examples with their parasitic gap counterparts in (96) and (97), we see that
            In the discussion of resumptive pronouns following (81),
            So far,
            Nevertheless,
            For one thing,
            Summarizing, then, we assume that
            A consequence of the approach just outlined is that
            Presumably,
            On our assumptions,
            It may be, then, that
            It must be emphasized, once again, that
            Let us continue to suppose that
            Notice, incidentally, that """
        # List of LEADINs to buy time.

        self.subjects = """ the notion of level of grammaticalness
            a case of semigrammaticalness of a different sort
            most of the methodological work in modern linguistics
            a subset of English sentences interesting on quite independent grounds
            the natural general principle that will subsume this case
            an important property of these three types of EC
            any associated supporting element
            the appearance of parasitic gaps in domains relatively inaccessible to ordinary extraction
            the speaker-hearer's linguistic intuition
            the descriptive power of the base component
            the earlier discussion of deviance
            this analysis of a formative as a pair of sets of features
            this selectionally introduced contextual feature
            a descriptively adequate grammar
            the fundamental error of regarding functional notions as categorial
            relational information
            the systematic use of complex symbols
            the theory of syntactic features developed earlier"""
        # List of SUBJECTs chosen for maximum professorial macho.

        self.verbs = """can be defined in such a way as to impose
            delimits
            suffices to account for
            cannot be arbitrary in
            is not subject to
            does not readily tolerate
            raises serious doubts about
            is not quite equivalent to
            does not affect the structure of
            may remedy and, at the same time, eliminate
            is not to be considered in determining
            is to be regarded as
            is unspecified with respect to
            is, apparently, determined by
            is necessary to impose an interpretation on
            appears to correlate rather closely with
            is rather different from"""
        #List of VERBs chosen for autorecursive obfuscation.

        self.objects = """ problems of phonemic and morphological analysis.
            a corpus of utterance tokens upon which conformity has been defined by the paired utterance test.
            the traditional practice of grammarians.
            the levels of acceptability from fairly high (e.g. (99a)) to virtual gibberish (e.g. (98d)).
            a stipulation to place the constructions into these various categories.
            a descriptive fact.
            a parasitic gap construction.
            the extended c-command discussed in connection with (34).
            the ultimate standard that determines the accuracy of any proposed grammar.
            the system of base rules exclusive of the lexicon.
            irrelevant intervening contexts in selectional rules.
            nondistinctness in the sense of distinctive feature theory.
            a general convention regarding the forms of the grammar.
            an abstract underlying order.
            an important distinction in language use.
            the requirement that branching is not tolerated within the dominance scope of a complex symbol.
            the strong generative capacity of the theory."""
        # List of OBJECTs selected for profound sententiousness.

        parts = []

        for part in (self.leadins, self.subjects, self.verbs, self.objects):
            phraselist = map(str.strip, part.splitlines())
            random.shuffle(phraselist)
            parts.append(phraselist)

        output = chain(*islice(izip(*parts), 0, times))
        self.output_text = textwrap.fill(' '.join(output), int(line_length))

    def __repr__(self):
        return self.output_text

    def get_output(self):
        return self.output_text

if __name__ == "__main__":
    try:
        if len(sys.argv) == 1:
            a = Chomsky()
            print a
        elif len(sys.argv) == 2:
            times = int(sys.argv[1])
            a = Chomsky(times)
            print a
        elif len(sys.argv) == 3:
            times = int(sys.argv[1])
            line_length = int(sys.argv[2])
            a = Chomsky(times, line_length)
            print a
        else:
            print 'Usage: python chomsky.py <number of sentences> <paragraph screen width>'
    except:
        print 'Usage: python chomsky.py <number of sentences> <paragraph screen width>'


text:
..
 This work is licensed under a Creative Commons Attribution 3.0 Unported
 License.

 http://creativecommons.org/licenses/by/3.0/legalcode

==========================================
Determinable supported boot device list
==========================================

This spec was proposed in the Liberty cycle.

See :doc:`../liberty-implemented/supported-boot-device-list`.


text:
package com.xinfan.blueblue.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.xinfan.blueblue.activity.context.LoginUserContext;
import com.xinfan.blueblue.activity.context.SystemConfigContext;
import com.xinfan.blueblue.activity.context.SystemSetContext;
import com.xinfan.blueblue.activity.context.VersionManager;
import com.xinfan.blueblue.activity.systemset.AboutUs;
import com.xinfan.blueblue.activity.systemset.MessageNumSelectActivity;
import com.xinfan.blueblue.activity.systemset.PaidSet;
import com.xinfan.blueblue.activity.systemset.ReputationSet;
import com.xinfan.blueblue.activity.systemset.SimilaritySet;
import com.xinfan.blueblue.dao.RequestCacheKeyHelper;
import com.xinfan.blueblue.request.AnsynHttpRequest;
import com.xinfan.blueblue.request.Constants;
import com.xinfan.blueblue.request.RequestSucessCallBack;
import com.xinfan.blueblue.request.Request;
import com.xinfan.blueblue.request.SharePreferenceUtil;
import com.xinfan.blueblue.request.ShareSystemSet;
import com.xinfan.blueblue.util.NumToChina;
import com.xinfan.blueblue.util.ToastUtil;
import com.xinfan.msgbox.http.service.vo.FunIdConstants;
import com.xinfan.msgbox.http.service.vo.param.BaseParam;
import com.xinfan.msgbox.http.service.vo.param.UserSetParam;
import com.xinfan.msgbox.http.service.vo.result.BaseResult;
import com.xinfan.msgbox.http.service.vo.result.UserResult;
import com.xinfan.msgbox.http.service.vo.result.UserSetResult;

public class SystemSetActivity extends Activity {
	public static SystemSetActivity instance;
	private CheckBox messageNoticeBtn;// 震动
	private CheckBox voiceBtn;// 震动
	private CheckBox vibrateBtn;// 震动
	private TextView receivenumText;// 消息数量
	private TextView similarityText;// 相似度
	private TextView paidText;// 相似度
	private TextView reputationText;// 相似度
	private TextView system_set_version_text;
	private Long userid;

	// private String ComplainText;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.system_set);
		messageNoticeBtn = (CheckBox) findViewById(R.id.system_messageNotice_btn);
		voiceBtn = (CheckBox) findViewById(R.id.System_voice_btn);
		vibrateBtn = (CheckBox) findViewById(R.id.system_vibrate_btn);
		receivenumText = (TextView) findViewById(R.id.receivenum_sytem_tv);
		similarityText = (TextView) findViewById(R.id.similarity_sytem_tv);
		paidText = (TextView) findViewById(R.id.paid_sytem_tv);
		reputationText = (TextView) findViewById(R.id.reputation_sytem_tv);
		system_set_version_text = (TextView) findViewById(R.id.system_set_version_text);
		system_set_version_text.setText(SystemConfigContext.getVersion(this));
		SharePreferenceUtil util = new SharePreferenceUtil(
				SystemSetActivity.this, Constants.USER_INFO);
		userid = util.getUserId();
		refresh();

		instance = this;
		// 监听是否接收消息
		messageNoticeBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				final boolean is = messageNoticeBtn.isChecked();
				SystemSetContext.setNewMsgNotify(SystemSetActivity.this, is, userid);
				SystemSetContext.setIsUpdate(SystemSetActivity.this, true, userid);
				refresh();
			}
		});
		// 监听震动开关
		vibrateBtn.setOnClickListener(new OnClickListener() {

			/* (non-Javadoc)
			 * @see android.view.View.OnClickListener#onClick(android.view.View)
			 */
			@Override
			public void onClick(View v) {
				final boolean is = vibrateBtn.isChecked();
				SystemSetContext.setVibrate(SystemSetActivity.this, is, userid);
				SystemSetContext.setIsUpdate(SystemSetActivity.this, true, userid);
				refresh();
			}
		});
		// 监听声音开关
		voiceBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				final boolean is = voiceBtn.isChecked();
				SystemSetContext.setVoice(SystemSetActivity.this, is, userid);
				SystemSetContext.setIsUpdate(SystemSetActivity.this, true, userid);
				refresh();
			}
		});
		// 监听接收数量设置
		LinearLayout receivenum = (LinearLayout) findViewById(R.id.receivenum_sytem_layout);
		receivenum.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent();
				intent.setClass(SystemSetActivity.this,
						MessageNumSelectActivity.class);
				startActivity(intent);
			}
		});
		// 监听消息相似度
		LinearLayout similarity = (LinearLayout) findViewById(R.id.similarity_sytem_layout);
		similarity.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent();
				intent.setClass(SystemSetActivity.this, SimilaritySet.class);
				startActivity(intent);
			}
		});
		// 监听有偿设置
		LinearLayout paid = (LinearLayout) findViewById(R.id.paid_sytem_layout);
		paid.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent();
				intent.setClass(SystemSetActivity.this, PaidSet.class);
				startActivity(intent);
			}
		});
		// 监听信誉等级
		LinearLayout reputation = (LinearLayout) findViewById(R.id.reputation_sytem_layout);
		reputation.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent();
				intent.setClass(SystemSetActivity.this, ReputationSet.class);
				startActivity(intent);
			}
		});
		// 监听系统升级
		LinearLayout goupSystem = (LinearLayout) findViewById(R.id.goup_system_layout);
		goupSystem.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				VersionManager manager = new VersionManager(
						SystemSetActivity.this);
				manager.checkManualUpdate();

			}
		});
		// 监听关于我们
		LinearLayout aboutUs = (LinearLayout) findViewById(R.id.about_us_layout);
		aboutUs.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent();
				intent.setClass(SystemSetActivity.this, AboutUs.class);
				startActivity(intent);
			}
		});

	}

	public void refresh() {

		boolean isupdate=SystemSetContext.getIsUpdate(SystemSetActivity.this, userid); //检查个人信息更新状态
		boolean messageNotice=SystemSetContext.getNewMsgNotify(SystemSetActivity.this, userid);
		boolean voice=SystemSetContext.getVoice(SystemSetActivity.this,userid);
		boolean vibrate=SystemSetContext.getVibrate(SystemSetActivity.this, userid);
		Integer receivenum=SystemSetContext.getReceivenum(SystemSetActivity.this, userid);
		Integer similarity=SystemSetContext.getSimilarity(SystemSetActivity.this, userid);
		Integer paid=SystemSetContext.getPaid(SystemSetActivity.this,userid);
		Integer reputation=SystemSetContext.getReputation(SystemSetActivity.this, userid);

		messageNoticeBtn.setChecked(messageNotice);
		voiceBtn.setChecked(voice);
		vibrateBtn.setChecked(vibrate);
		receivenumText.setText(receivenum+"条");
		similarityText.setText(NumToChina.NumToChina(similarity)+"级");
		if(paid==0){
			paidText.setText("全部");
		}else{
			paidText.setText(paid+"元以上");
		}
		if(reputation==0){
		reputationText.setText("全部");
		}else{
			reputationText.setText(reputation+"星");
		}

		if(isupdate){//同步服务器
		Request request = new Request(FunIdConstants.SET_USERSET);
		UserSetParam param = new UserSetParam();
		param.setUserId(userid);
		if (messageNotice) {
			param.setNewMsgNotify(1);
		} else {
			param.setNewMsgNotify(0);
		}
		if (vibrate) {
			param.setVibrate(1);
		} else {
			param.setVibrate(0);
		}
		if (voice) {
			param.setVoice(1);
		} else {
			param.setVoice(0);
		}
		param.setMaxCount(receivenum);
		param.setSimilarLevel(similarity);
		param.setMinAmmount(paid);
		param.setMinCredit(reputation);
		request.setParam(param);

		request.setCache(true);
		request.setCacheKey(RequestCacheKeyHelper
				.generateSystemSetCacheKey(param));

		AnsynHttpRequest.requestSimpleByPost(this, request, new RequestSucessCallBack() {

			public void call(Request data) {

			BaseResult result = (BaseResult) data.getResult();
			if(result.getResult()==1){
				SystemSetContext.setIsUpdate(SystemSetActivity.this, false, userid);
				ToastUtil.showMessage(SystemSetActivity.this,"个人设置已生效");
			}else{
				ToastUtil.showMessage(SystemSetActivity.this,result.getMsg());
			}

		}
				});

		}
	}

	public void SystemSetBack(View v) { // 返回
		this.finish();
	}

}


text: 2009-2014, Hospital La Carlota © Iglesia Adventista del Séptimo Día


text:
require File.expand_path('../../spec_helper', __FILE__)
require File.expand_path('../fixtures/super', __FILE__)

describe "The super keyword" do
  it "calls the method on the calling class" do
    Super::S1::A.new.foo([]).should == ["A#foo","A#bar"]
    Super::S1::A.new.bar([]).should == ["A#bar"]
    Super::S1::B.new.foo([]).should == ["B#foo","A#foo","B#bar","A#bar"]
    Super::S1::B.new.bar([]).should == ["B#bar","A#bar"]
  end

  it "searches the full inheritence chain" do
    Super::S2::B.new.foo([]).should == ["B#foo","A#baz"]
    Super::S2::B.new.baz([]).should == ["A#baz"]
    Super::S2::C.new.foo([]).should == ["B#foo","C#baz","A#baz"]
    Super::S2::C.new.baz([]).should == ["C#baz","A#baz"]
  end

  it "searches class methods" do
    Super::S3::A.new.foo([]).should == ["A#foo"]
    Super::S3::A.foo([]).should == ["A.foo"]
    Super::S3::A.bar([]).should == ["A.bar","A.foo"]
    Super::S3::B.new.foo([]).should == ["A#foo"]
    Super::S3::B.foo([]).should == ["B.foo","A.foo"]
    Super::S3::B.bar([]).should == ["B.bar","A.bar","B.foo","A.foo"]
  end

  it "calls the method on the calling class including modules" do
    Super::MS1::A.new.foo([]).should == ["ModA#foo","ModA#bar"]
    Super::MS1::A.new.bar([]).should == ["ModA#bar"]
    Super::MS1::B.new.foo([]).should == ["B#foo","ModA#foo","ModB#bar","ModA#bar"]
    Super::MS1::B.new.bar([]).should == ["ModB#bar","ModA#bar"]
  end

  it "searches the full inheritence chain including modules" do
    Super::MS2::B.new.foo([]).should == ["ModB#foo","A#baz"]
    Super::MS2::B.new.baz([]).should == ["A#baz"]
    Super::MS2::C.new.baz([]).should == ["C#baz","A#baz"]
    Super::MS2::C.new.foo([]).should == ["ModB#foo","C#baz","A#baz"]
  end

  it "can resolve to different methods in an included module method" do
    Super::MultiSuperTargets::A.new.foo.should == :BaseA
    Super::MultiSuperTargets::B.new.foo.should == :BaseB
  end

  it "searches class methods including modules" do
    Super::MS3::A.new.foo([]).should == ["A#foo"]
    Super::MS3::A.foo([]).should == ["ModA#foo"]
    Super::MS3::A.bar([]).should == ["ModA#bar","ModA#foo"]
    Super::MS3::B.new.foo([]).should == ["A#foo"]
    Super::MS3::B.foo([]).should == ["B.foo","ModA#foo"]
    Super::MS3::B.bar([]).should == ["B.bar","ModA#bar","B.foo","ModA#foo"]
  end

  it "searches BasicObject from a module for methods defined there" do
    Super::IncludesFromBasic.new.__send__(:foobar).should == 43
  end

  it "searches BasicObject through another module for methods defined there" do
    Super::IncludesIntermediate.new.__send__(:foobar).should == 42
  end

  it "calls the correct method when the method visibility is modified" do
    Super::MS4::A.new.example.should == 5
  end

  it "calls the correct method when the superclass argument list is different from the subclass" do
    Super::S4::A.new.foo([]).should == ["A#foo"]
    Super::S4::B.new.foo([],"test").should == ["B#foo(a,test)", "A#foo"]
  end

  it "raises an error error when super method does not exist" do
    sup = Class.new
    sub_normal = Class.new(sup) do
      def foo
        super()
      end
    end
    sub_zsuper = Class.new(sup) do
      def foo
        super
      end
    end

    lambda {sub_normal.new.foo}.should raise_error(NoMethodError, /super/)
    lambda {sub_zsuper.new.foo}.should raise_error(NoMethodError, /super/)
  end

  it "uses given block even if arguments are passed explicitly" do
    c1 = Class.new do
      def m
        yield
      end
    end
    c2 = Class.new(c1) do
      def m(v)
        super()
      end
    end

    c2.new.m(:dump) { :value }.should == :value
  end

  it "calls the superclass method when in a block" do
    Super::S6.new.here.should == :good
  end

  it "calls the superclass method when initial method is defined_method'd" do
    Super::S7.new.here.should == :good
  end

  it "can call through a define_method multiple times (caching check)" do
    obj = Super::S7.new

    2.times do
      obj.here.should == :good
    end
  end

  it "supers up appropriate name even if used for multiple method names" do
    sup = Class.new do
      def a; "a"; end
      def b; "b"; end
    end

    sub = Class.new(sup) do
      [:a, :b].each do |name|
        define_method name do
          super()
        end
      end
    end

    sub.new.a.should == "a"
    sub.new.b.should == "b"
    sub.new.a.should == "a"
  end

  it "raises a RuntimeError when called with implicit arguments from a method defined with define_method" do
    super_class = Class.new do
      def a(arg)
        arg
      end
    end

    klass = Class.new super_class do
      define_method :a do |arg|
        super
      end
    end

    lambda { klass.new.a(:a_called) }.should raise_error(RuntimeError)
  end

  # Rubinius ticket github#157
  it "calls method_missing when a superclass method is not found" do
    Super::MM_B.new.is_a?(Hash).should == false
  end

  # Rubinius ticket github#180
  it "respects the original module a method is aliased from" do
    Super::Alias3.new.name3.should == [:alias2, :alias1]
  end

  it "sees the included version of a module a method is alias from" do
    Super::AliasWithSuper::Trigger.foo.should == [:b, :a]
  end

  it "find super from a singleton class" do
    obj = Super::SingletonCase::Foo.new
    def obj.foobar(array)
      array << :singleton
      super
    end
    obj.foobar([]).should == [:singleton, :foo, :base]
  end

  it "finds super on other objects if a singleton class aliased the method" do
    orig_obj = Super::SingletonAliasCase::Foo.new
    orig_obj.alias_on_singleton
    orig_obj.new_foobar([]).should == [:foo, :base]
    Super::SingletonAliasCase::Foo.new.foobar([]).should == [:foo, :base]
  end

  it "passes along modified rest args when they weren't originally empty" do
    Super::RestArgsWithSuper::B.new.a("bar").should == ["bar", "foo"]
  end

  it "passes along modified rest args when they were originally empty" do
    Super::RestArgsWithSuper::B.new.a.should == ["foo"]
  end

  it "invokes methods from a chain of anonymous modules" do
    Super::AnonymousModuleIncludedTwice.new.a([]).should == ["anon", "anon", "non-anon"]
  end

  it "without explicit arguments can accept a block but still pass the original arguments" do
    Super::ZSuperWithBlock::B.new.a.should == 14
  end

  it "passes along block via reference to method expecting a reference" do
    Super::ZSuperWithBlock::B.new.b.should == [14, 15]
  end

  it "passes along a block via reference to a method that yields" do
    Super::ZSuperWithBlock::B.new.c.should == 16
  end

  it "without explicit arguments passes optional arguments that have a default value" do
    Super::ZSuperWithOptional::B.new.m(1, 2).should == 14
  end

  it "without explicit arguments passes optional arguments that have a non-default value" do
    Super::ZSuperWithOptional::B.new.m(1, 2, 3).should == 3
  end

  it "without explicit arguments passes optional arguments that have a default value but were modified" do
    Super::ZSuperWithOptional::C.new.m(1, 2).should == 100
  end

  it "without explicit arguments passes optional arguments that have a non-default value but were modified" do
    Super::ZSuperWithOptional::C.new.m(1, 2, 3).should == 100
  end

  it "without explicit arguments passes rest arguments" do
    Super::ZSuperWithRest::B.new.m(1, 2, 3).should == [1, 2, 3]
  end

  it "without explicit arguments passes rest arguments including any modifications" do
    Super::ZSuperWithRest::B.new.m_modified(1, 2, 3).should == [1, 14, 3]
  end

  it "without explicit arguments passes arguments and rest arguments" do
    Super::ZSuperWithRestAndOthers::B.new.m(1, 2, 3, 4, 5).should == [3, 4, 5]
  end

  it "without explicit arguments passes arguments and rest arguments including any modifications" do
    Super::ZSuperWithRestAndOthers::B.new.m_modified(1, 2, 3, 4, 5).should == [3, 14, 5]
  end

  it "without explicit arguments that are '_'" do
    Super::ZSuperWithUnderscores::B.new.m(1, 2).should == [1, 2]
  end

  it "without explicit arguments that are '_' including any modifications" do
    Super::ZSuperWithUnderscores::B.new.m_modified(1, 2).should == [14, 2]
  end

  describe 'when using keyword arguments' do
    it 'passes any given keyword arguments to the parent' do
      b = Super::KeywordArguments::B.new
      b.foo(:number => 10).should == {:number => 10}
    end

    it "passes any given keyword arguments including optional and required ones to the parent" do
      class Super::KeywordArguments::C
        eval <<-RUBY
        def foo(a:, b: 'b', **)
          super
        end
        RUBY
      end
      c = Super::KeywordArguments::C.new

      c.foo(a: 'a', c: 'c').should == {a: 'a', b: 'b', c: 'c'}
    end

    it 'does not pass any keyword arguments to the parent when none are given' do
      b = Super::KeywordArguments::B.new
      b.foo.should == {}
    end

    describe 'when using splat arguments' do
      it 'passes splat arguments and keyword arguments to the parent' do
        b = Super::SplatAndKeyword::B.new

        b.foo('bar', baz: true).should == [['bar'], {baz: true}]
      end
    end
  end
end


text:
<?php

/**
 */
class Admin_Form_Profile extends Zend_Form
{
    public function init()
    {
        $translator = \Zend_Registry::get('container')->getService('translator');

        $this->setAttrib('enctype', 'multipart/form-data');

        $this->addElement('file', 'image', array(
            'label' => $translator->trans('Picture', array(), 'users'),
        ));

        $this->addElement('submit', 'submit', array(
            'label' => 'Save',
            'ignore' => true,
            'order' => 99,
        ));
    }
}


text:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

			<title>Docs For Class InstallController</title>
			<link rel="stylesheet" href="../media/stylesheet.css" />
			<meta http-equiv='Content-Type' content='text/html; charset=iso-8859-1'/>

 InstallController

Description

					Description |
													Vars (details)
						|											Methods (details)

Manages the application installation

copyright: Copyright (c) 2009 Joobsbox. (http://www.joobsbox.com)

license: http://www.joobsbox.com/joobsbox-php-license

			Located in /Controllers/InstallController.php (line 21)

Zend_Controller_Action
   |
   --InstallController

Variable Summary

			Description |
						Vars (details)
							|
									Methods (details)

					mixed
					$_model

Method Summary

			Description |
																		Vars (details)

				|
						Methods (details)

											void
										indexAction
										()

											void
										init
										()

											void
										step1Action
										()

											void
										step2Action
										()

											void
										step3Action
										()

Variables

			Description |
										Vars (details)

										|
									Methods (details)

			mixed
			$_model
						(line 22)

access: protected

Methods

			Description |
															Vars (details)
														Methods (details)

		indexAction (line 31)

access: public

		void

			indexAction

				()

		init (line 24)

access: public

		void

			init

				()

		step1Action (line 38)

todo: add timezone box using timezone_identifiers_list()

access: public

		void

			step1Action

				()

		step2Action (line 89)

todo: install first user

todo: install base database schema

access: public

		void

			step2Action

				()

		step3Action (line 120)

access: public

		void

			step3Action

				()

		Documentation generated on Mon, 25 May 2009 14:19:08 +0300 by phpDocumentor 1.4.2


text:
class AddContentIdFieldToAttachments < ActiveRecord::Migration
  def change
    add_column :attachments, :content_id, :string
  end
end


text:
package uic

import (
	"github.com/Cepave/open-falcon-backend/modules/fe/g"
	"github.com/Cepave/open-falcon-backend/modules/fe/http/base"
	. "github.com/Cepave/open-falcon-backend/modules/fe/model/uic"
	"github.com/Cepave/open-falcon-backend/modules/fe/utils"
	"strings"
)

type TeamController struct {
	base.BaseController
}

func (this *TeamController) Teams() {
	query := strings.TrimSpace(this.GetString("query", ""))
	if utils.HasDangerousCharacters(query) {
		this.ServeErrJson("query is invalid")
		return
	}

	per := this.MustGetInt("per", 10)
	me := this.Ctx.Input.GetData("CurrentUser").(*User)

	teams, err := QueryMineTeams(query, me.Id)
	if err != nil {
		this.ServeErrJson("occur error " + err.Error())
		return
	}

	total, err := teams.Count()
	if err != nil {
		this.ServeErrJson("occur error " + err.Error())
		return
	}

	pager := this.SetPaginator(per, total)
	teams = teams.Limit(per, pager.Offset())

	var ts []Team
	_, err = teams.All(&ts)
	if err != nil {
		this.ServeErrJson("occur error " + err.Error())
		return
	}

	this.Data["Teams"] = ts
	this.Data["Query"] = query
	this.Data["Me"] = me
	this.Data["IamRoot"] = me.Name == "root"
	this.Data["Shortcut"] = g.Config().Shortcut
	this.TplName = "team/list.html"
}

func (this *TeamController) CreateTeamGet() {
	this.Data["Shortcut"] = g.Config().Shortcut
	this.TplName = "team/create.html"
}

func (this *TeamController) CreateTeamPost() {
	name := strings.TrimSpace(this.GetString("name", ""))
	if name == "" {
		this.ServeErrJson("name is blank")
		return
	}

	if utils.HasDangerousCharacters(name) {
		this.ServeErrJson("name is invalid")
		return
	}

	resume := strings.TrimSpace(this.GetString("resume", ""))
	if utils.HasDangerousCharacters(resume) {
		this.ServeErrJson("resume is invalid")
		return
	}

	t := ReadTeamByName(name)
	if t != nil {
		this.ServeErrJson("name is already existent")
		return
	}

	me := this.Ctx.Input.GetData("CurrentUser").(*User)
	lastId, err := SaveTeamAttrs(name, resume, me.Id)
	if err != nil {
		this.ServeErrJson("occur error " + err.Error())
		return
	}

	uids := strings.TrimSpace(this.GetString("users", ""))
	if utils.HasDangerousCharacters(uids) {
		this.ServeErrJson("uids is invalid")
		return
	}

	err = PutUsersInTeam(lastId, uids)
	if err != nil {
		this.ServeErrJson("occur error " + err.Error())
	} else {
		this.ServeOKJson()
	}
}

func (this *TeamController) Users() {
	teamName := strings.TrimSpace(this.GetString("name", ""))
	if teamName == "" {
		this.ServeErrJson("name is blank")
		return
	}

	this.Data["json"] = map[string]interface{}{
		"users": MembersByTeamName(teamName),
		"msg":   "",
	}
	this.ServeJSON()
}

func (this *TeamController) DeleteTeam() {
	me := this.Ctx.Input.GetData("CurrentUser").(*User)
	targetTeam := this.Ctx.Input.GetData("TargetTeam").(*Team)
	if !me.CanWrite(targetTeam) {
		this.ServeErrJson("no privilege")
		return
	}

	err := targetTeam.Remove()
	if err != nil {
		this.ServeErrJson(err.Error())
		return
	}

	this.ServeOKJson()
}

func (this *TeamController) EditGet() {
	targetTeam := this.Ctx.Input.GetData("TargetTeam").(*Team)
	this.Data["TargetTeam"] = targetTeam
	this.Data["Shortcut"] = g.Config().Shortcut
	this.TplName = "team/edit.html"
}

func (this *TeamController) EditPost() {
	targetTeam := this.Ctx.Input.GetData("TargetTeam").(*Team)
	resume := this.MustGetString("resume", "")
	userIdstr := this.MustGetString("users", "")

	if utils.HasDangerousCharacters(resume) || utils.HasDangerousCharacters(userIdstr) {
		this.ServeErrJson("parameter resume or users is invalid")
		return
	}

	if targetTeam.Resume != resume {
		targetTeam.Resume = resume
		targetTeam.Update()
	}

	this.AutoServeError(targetTeam.UpdateUsers(userIdstr))
}

// for portal api: query team
func (this *TeamController) Query() {
	query := this.MustGetString("query", "")
	limit := this.MustGetInt("limit", 10)

	qs := QueryAllTeams(query)
	var ts []Team
	qs.Limit(limit).All(&ts)
	this.Data["json"] = map[string]interface{}{
		"msg":   "",
		"teams": ts,
	}
	this.ServeJSON()
}

func (this *TeamController) All() {
	this.Redirect("/me/teams", 301)
}


text:
using UnityEngine;
using System.Collections;

public class GazeScaleTo : GazeBehaviour
{
    [SerializeField] private Vector3 scale;
    [SerializeField] private float speed;
    [SerializeField] private Space space;
    [SerializeField] private iTween.EaseType easeType;
    [SerializeField] private GameObject scaleObject;

    private bool hasGaze;
    private Vector3 startScale;

    void Awake()
    {
        if ( scaleObject == null ) { scaleObject = gameObject; }
        startScale = scaleObject.transform.localScale;

    }

    protected override void DoGazeEnter( GazeHit hit )
    {
        iTween.ScaleTo( scaleObject, iTween.Hash(
                            "name", "gazeScaleTo",
                            "scale", scale,
                            "speed", speed
                        )
                      );
    }

    protected override void DoGazeExit( GazeHit hit )
    {
        iTween.ScaleTo( scaleObject, iTween.Hash(
                            "scale", startScale,
                            "speed", speed
                        )
                      );
    }

    protected override void DoGazeStop( GazeHit hit )
    {
        iTween.StopByName( "gazeScaleTo" );
    }
}


text:
export default interface CartTotalSegmentsItem {
  code: string,
  title: string,
  value: number,
  area?: string,
  extension_attributes?: object
}


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

namespace FMI.WeAzure.Boxing.Contracts.Interfaces
{
    public interface IRequest : IRequest<Unit>
    {
    }

    public interface IRequest<out TResponse>
    {

    }
}


text:
package com.jsonde.client.domain;

public class TopMethodCall extends DomainObject {

    private long methodCallId;
    private long hashCode;
    private long count;

    public long getMethodCallId() {
        return methodCallId;
    }

    public void setMethodCallId(long methodCallId) {
        this.methodCallId = methodCallId;
    }

    public long getHashCode() {
        return hashCode;
    }

    public void setHashCode(long hashCode) {
        this.hashCode = hashCode;
    }

    public long getCount() {
        return count;
    }

    public void setCount(long count) {
        this.count = count;
    }

}


text:
using System;
using System.Reflection;

public class DefineClassPerson
{
    public static void Main()
    {
        Type personType = typeof(Person);
        FieldInfo[] fields = personType.GetFields(BindingFlags.Public | BindingFlags.Instance);
        Console.WriteLine(fields.Length);

        Person firstPerson = new Person();
        firstPerson.name = "Pesho";
        firstPerson.age = 20;

        Person secondPerson = new Person()
        {
            name = "Gosho",
            age = 18
        };

        Person thirdPerson = new Person()
        {
            name = "Stamat",
            age = 43
        };
        Console.WriteLine(secondPerson.name);

    }
}


text:
{% extends "translator/page.html" %}

{% block subtitle %}{{ _('Translator') }}{% endblock %}

{% block breadcrumb_content %}

{% link_for _('Translator'), controller='ckanext.lait.plugin:LaitController', action='translator' %}

{% endblock %}

{% block primary_content_inner %}
	<form class="search-form no-bottom-border" role="search" onsubmit='return false;' data-module="select-switch">

	        <input id="search-filter" type="text" class="search" name="q" value="{{ q }}" autocomplete="off" placeholder="{{ _('Search within terms') }}..." >
	        <button type="button" onclick="search();">

	        </button>

				     {{ _('terms found') }}

{{ _('Translated') }}
	    			<input id="search-translated" type="checkbox" onclick="search();" style="width:20px; height:20px; margin:-18px 20px 0 5px;" checked>

{{ _('Not translated') }}
					<input id="search-not-translated" type="checkbox" onclick="search();" style="width:20px; height:20px; margin:-18px 0 0 5px" checked>

	  		<button type="button" class="close" data-dismiss="alert">×</button>
		  	{{_('Translated')}}  {{ _('terms on')}}  (%)

	</form>

					#

    	<form role="form" onsubmit='return false;' style="margin:0;">

		        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

{{_('Translation panel')}}

{{_('Original text')}}:

{{_('Translated text')}}:

				<textarea class="form-control" id="term-translation" style="resize: vertical;width:97%;margin-top:5px"
					placeholder="{{_('Provide a translation for the selected text')}}" rows="5"></textarea>

		    	<button type="submit" class="btn" data-dismiss="modal">{{_('Close')}}</button>
		        <button type="submit" class="btn btn-primary" onclick="insertTranslation();">{{_('Save')}}</button>

	    </form>

    {{_('Translation successfully saved')}}
    {{_('Error saving translation')}}
    {{ c.userobj.apikey }}
    {{ c.userobj.name }}
{% endblock %}


text:
package co.uk.sussexsoftware.buffer;

import java.util.Dictionary;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import org.osgi.service.cm.ConfigurationException;
import org.osgi.service.cm.ManagedService;

/**
 *
 * @author rodm
 */
public class MBeanSizeCheck implements ManagedService {

    private final String mBeanName;
    private final MBeanServer mBeanServer;
    private Dictionary<String, ?> bufferSizes;

    /**
     *
     *  Note:  this class uses the Mbean server within Karaf, which has an MBean guard requiring RBAC
     *  Therefore to access from with the process the MBean must be white listed in \auth\jmx.acl.whiitelist.cfg
     *
     * @param mBeanServer
     * @param amqBrokerName
     */
    public MBeanSizeCheck(MBeanServer mBeanServer, String amqBrokerName)
    {
       this.mBeanServer = mBeanServer;

       // Build the Object Name for the mBean as "org.apache.activemq:type=Broker,brokerName=<amqBrokerName>,destinationType=Queue,destinationName="
       // name of destination is added later by the retriveBufferSize method
       StringBuilder mBeanNameBuilder = new StringBuilder();
       mBeanNameBuilder.append("org.apache.activemq:type=Broker,brokerName=");
       mBeanNameBuilder.append(amqBrokerName);
       mBeanNameBuilder.append(",destinationType=Queue,destinationName=");
       mBeanName=mBeanNameBuilder.toString();
    }

    /**
     *
     * @param bufferName
     * @return
     * @throws Exception
     */
    public boolean isBufferFull(String bufferName) throws Exception
    {
        long maxBufferSize = Long.parseLong((String) bufferSizes.get(bufferName+".size"));
        long bufferSize = retriveBufferSize(bufferName);
        return (bufferSize > maxBufferSize);
    }

    private long retriveBufferSize(String bufferName) throws Exception
    {
        // Assuming the RuntimeMXBean has been registered in mbs
        String objectName = mBeanName+bufferName;
        ObjectName oname = new ObjectName(objectName);

        // Get platform-specific attribute "TotalPhysicalMemorySize"
        return (Long) mBeanServer.getAttribute(oname, "QueueSize");
    }

    /**
     * This implements the ManagedService interface for obtaining a copy of
     * property set that contains the buffer sizing values
     *
     * @param dctnr
     * @throws ConfigurationException
     */
    public void updated(Dictionary<String, ?> dctnr) throws ConfigurationException
    {
        this.bufferSizes = dctnr;
    }
}


text:
<?php

namespace League\Uri\Modifiers;

use League\Uri\Modifiers\Filters\Segment;

/**
 * Prepend a path to the URI path
 *
 * @package League.uri
 * @author  Ignace Nyamagana Butera <nyamsprod@gmail.com>
 * @since   4.0.0
 */
class PrependSegment extends AbstractPathModifier
{
    use Segment;

    /**
     * New instance
     *
     * @param string $segment
     */
    public function __construct($segment)
    {
        $this->segment = $this->filterSegment($segment);
    }

    /**
     * Modify a URI part
     *
     * @param string $str the URI part string representation
     *
     * @return string the modified URI part string representation
     */
    protected function modify($str)
    {
        return (string) $this->segment
            ->modify($str)
            ->prepend((string) $this->segment);
    }
}


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

package com.google.gerrit.pgm.util;

import com.google.gerrit.extensions.events.LifecycleListener;
import com.google.gerrit.lifecycle.LifecycleModule;
import com.google.gerrit.reviewdb.server.ReviewDb;
import com.google.gwtorm.server.OrmException;
import com.google.gwtorm.server.SchemaFactory;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.ProvisionException;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Module to bind a single {@link ReviewDb} instance per thread.
 * <p>
 * New instances are opened on demand, but are closed only at shutdown.
 */
class PerThreadReviewDbModule extends LifecycleModule {
  private final SchemaFactory<ReviewDb> schema;

  @Inject
  PerThreadReviewDbModule(SchemaFactory<ReviewDb> schema) {
    this.schema = schema;
  }

  @Override
  protected void configure() {
    final List<ReviewDb> dbs = Collections.synchronizedList(
        new ArrayList<ReviewDb>());
    final ThreadLocal<ReviewDb> localDb = new ThreadLocal<>();

    bind(ReviewDb.class).toProvider(new Provider<ReviewDb>() {
      @Override
      public ReviewDb get() {
        ReviewDb db = localDb.get();
        if (db == null) {
          try {
            db = schema.open();
            dbs.add(db);
            localDb.set(db);
          } catch (OrmException e) {
            throw new ProvisionException("unable to open ReviewDb", e);
          }
        }
        return db;
      }
    });
    listener().toInstance(new LifecycleListener() {
      @Override
      public void start() {
        // Do nothing.
      }

      @Override
      public void stop() {
        for (ReviewDb db : dbs) {
          db.close();
        }
      }
    });
  }
}


text:
// Karma configuration
// Generated on 2016-07-13

module.exports = function(config) {
  'use strict';

  config.set({
    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // base path, that will be used to resolve files and exclude
    basePath: '../',

    // testing framework to use (jasmine/mocha/qunit/...)
    // as well as any additional frameworks (requirejs/chai/sinon/...)
    frameworks: [
      'jasmine'
    ],

    // list of files / patterns to load in the browser
    files: [
      // bower:js
      'bower_components/jquery/dist/jquery.js',
      'bower_components/angular/angular.js',
      'bower_components/bootstrap/dist/js/bootstrap.js',
      'bower_components/angular-route/angular-route.js',
      'bower_components/ng-file-upload/ng-file-upload.js',
      'bower_components/aws-sdk/dist/aws-sdk.js',
      'bower_components/aws-cognito-sdk/index.js',
      'bower_components/amazon-cognito-identity/index.js',
      'bower_components/angular-mocks/angular-mocks.js',
      // endbower

      'app/scripts/cognito-auth/aws-cognito-sdk.min.js',
      'app/scripts/cognito-auth/amazon-cognito-identity.min.js',
      'app/scripts/cognito-auth/cognito-auth.js',
      'app/scripts/cognito-auth/cognito-user.service.js',

      'app/scripts/app.js',
      'app/scripts/user/user.component.js',
      'app/scripts/user/user-login.component.js',
      'app/scripts/user/user-logout.component.js',
      'app/scripts/recordings/recordings.component.js',
      'app/scripts/recordings/recordings.occasional-series.component.js',
      'app/scripts/recordings/recordings.list.component.js',
      'app/scripts/recordings/recording.item.component.js',
      'app/scripts/recordings/recordings.service.js',
      'app/scripts/upload/upload.service.js',
      'app/scripts/uploader/uploader.component.js',
      // test stuff
      'app/scripts/**/*.mock.js',
      'app/scripts/**/*.spec.js'
    ],

    // list of files / patterns to exclude
    exclude: [
    ],

    // web server port
    port: 9021,

    // Start these browsers, currently available:
    // - Chrome
    // - ChromeCanary
    // - Firefox
    // - Opera
    // - Safari (only Mac)
    // - PhantomJS
    // - IE (only Windows)
    browsers: [
      'PhantomJS'
    ],

    // Which plugins to enable
    plugins: [
      'karma-phantomjs-launcher',
      'karma-jasmine'
    ],

    // Continuous Integration mode
    // if true, it capture browsers, run tests and exit
    singleRun: false,

    colors: true,

    // level of logging
    // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
    logLevel: config.LOG_INFO,

    // Uncomment the following lines if you are using grunt's server to run the tests
    // proxies: {
    //   '/': 'http://localhost:9000/'
    // },
    // URL root prevent conflicts with the site root
    // urlRoot: '_karma_'
  });
};


text:
/*
* @Author: aminhuang
* @Date:   2016-03-02 19:37:06
* @Last Modified by:   aminhuang
* @Last Modified time: 2016-03-08 16:24:16
*/

'use strict';

import React,{
    AppRegistry,
    Component,
    StyleSheet,
    View,
    Text,
    Image,
    TextInput,
    ScrollView,
    TouchableOpacity
} from 'react-native';

import FirstPageComponent from './FirstPageComponent';
import ClassInitComponent from './ClassInitComponent';

const AJAX_URL = "http://120.27.97.93:12327/ajax";

var serializeJSON = function(data) {
  return Object.keys(data).map(function (keyName) {
    return encodeURIComponent(keyName) + '=' + encodeURIComponent(data[keyName])
  }).join('&');
}

class LoginComponent extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            stu_id: null,
            password: null,
            error: "",
        }
    }
    // 自定义方法, 异步获取方法
    fetchData() {
        fetch(url)
            .then((response) => response.json())
            .then((responseData) => {
                this.setState({
                    test: responseData.data.stu.name,
                });
            })
            .done();
    }
    _pressButton() {
        var _this = this;
        const { navigator } =  this.props;

        if(this.state.stu_id && this.state.password) {
            this.setState({error: ""});

            fetch(AJAX_URL, {
                method: 'post',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
                },
                body: serializeJSON({
                    action : "login",
                    id: this.state.stu_id,
                    pwd: this.state.password,
                })
            })
            .then((response) => {
                return response.json();
            })
            .then((responseData) => {
                console.log(responseData);
                if(navigator) {
                    navigator.push({
                        name: 'ClassInitComponent',
                        component: ClassInitComponent,
                        params: {
                            stu_id: this.state.stu_id
                        }
                    })
                }

            })
            .catch((error) => {
                console.log(error);
                this.setState({error: error});
            })
            .done();
        } else {
            this.setState({error: "请填写完整"});
        }

    }

    render() {
        return (
            <ScrollView
                contentContainerStyle={{flex:1}}
                keyboardDismissMode='on-drag'
                keyboardShouldPersistTaps={false}
            >
                <View style={styles.container}>
                    <Image
                        source={{uri:'http://oss-hz.qianmi.com/qianmicom/u/cms/qmwww/201511/03102524l6ur.png'}}
                        style={styles.logo}
                    />
                    <TextInput
                        ref={(stu_id) => this.stu_id = stu_id}
                        onChangeText = {(text) => this.setState({stu_id: text})}
                        onFocus={() => this.stu_id.focus()}
                        style={styles.input}
                        placeholder='id' />
                    <TextInput
                        ref={(password) => this.password = password}
                        onChangeText = {(text) => this.setState({password: text})}
                        onFocus={() => this.password.focus()}
                        style={styles.input}
                        placeholder='password'
                        password={true} />

                    <Text>{this.state.error}</Text>

                    <TouchableOpacity style={styles.btn} onPress={this._pressButton.bind(this)}>
                        <Text sytle={styles.text}>登录</Text>
                    </TouchableOpacity>
                </View>
            </ScrollView>
        )

    }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    // justifyContent: 'center',
    paddingLeft: 10,
    paddingRight: 10,
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  logo: {
    width: 160,
    height: 160,
    marginTop: 100
  },
  input: {
    height: 40,
    marginTop: 10,
    borderWidth: 1,
    borderRadius: 5,
    borderColor: 'lightblue'
  },
  text: {
    fontWeight: 'bold',
    fontSize: 14,
    color: '#FFF'
  },
  btn: {
    alignSelf: 'stretch', // 覆盖父样式
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: '#3333FF',
    height: 40,
    borderRadius: 5,
    marginTop: 10
  }
});

export default LoginComponent


text:
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">

    <title>JEmacs and the gnu.jemacs.buffer Package</title>

Provides various building blocks for building an Emacs-like text editor.
It also provides a number of Scheme procedures that have the same name
and similar functionality as the Emacs Lisp functions.
Somewhat out of date.
Check the JEmacs home page
for more information.

It uses the Swing tool-kit.

Plan

The plan is to use
this together with the (unfinished) gnu.jemacs.lang
package to provide a fully-functional re-implementation of
Emacs Lisp which compiles to Java bytecodes.
I'm hoping volunteers will help me make "JEmacs" into something
useful.  I have fairly clear ideas about much of what need to be
done.  Contact me if you are interested.

Home page

There is now a JEmacs home page.
Also check out the
Kawa home page.

Screen snapshot

There is a now a
teaser screen snapshot.

Status

Very unfinished proof of concerpt.
It is a functional but very minimal editor.
Many of the core Emacs concepts (keymaps, windows, frames,
buffers, markers) are implemented, and generally in such a way as
to provide the standard Emacs semantics.  There are Scheme functions
with the same name and similar behavior as the standard Emacs Lisp
functions.  However, there is only a very limited set of core "editing"
commands, and no searching commands.  And it is not
robust or reliable.

To-do

A couple of things volunteers might start with
(but let me know before you spend serious time on any of these):

Implement more of the editing commands:  Insert/delete/forward/backward
word/line.

Display the modeline in inverse video, but extend it to the full
window width.

Come up with a design for narrowing a buffer.  One possibility
is to use some kind of invisible style for the text outside the narrowing.
But I think a more flexible design would use an "IndirectDocument" class
that refers to a sub-range of a buffer.  This would help with "Indirect
Buffers", and might be flexible and elegant in general.

Perhaps Buffer should inherit from Document (or rather
DefaultStyledDocument).  However, that might lose some flexibility.

Needs methods to control Window scrolling.

Think about how to map extents and faces to Swing attributes
and styles.

Decide how to implement Emacs strings.
Initially, we'll use kawa.lang.FString, but we do want to support strings
with extents and text properties.

Usage

These classes depend on Swing, so make sure you have Swing available.
Then make sure you have a version of the Kawa classes that contains
the gnu.jemacs.buffer classes.  (In other words,
Kawa needs to have been configure --with-swing support.)
Then just start Kawa in the usual way:

java kawa.repl

Then evaluate:

(emacs)

That brings up a Emacs window.

You can do (split-window) to create new (sub-)windows
in an existing frame; type (make-frame) to create
a new frame (to-level window), or do (get-buffer-create NAME)
to create a new buffer.
Note also how ctrl/B and ctrl/F have been
bound to the correct functions.  For other working key-bindings,
look for the calls to define-key in emacs.scm.

The call (scheme-swing-window) creates a new Scheme
interaction window.

License

Same as the package gnu.expr:  Modified Gnu Public License.
See the file COPYING.
For now, the copyright holder is Per Bothner;  in the future it may
make more sense to make the FSF the copyright owner, since the plan
is to use a lot of the existing ELisp packages once ELisp support
is complete.

Author

Per Bothner,
<tt><bothner@gnu.org></tt>


text:
Date.CultureInfo = {
	/* Culture Name */
    name: "hr-BA",
    englishName: "Croatian (Bosnia and Herzegovina)",
    nativeName: "hrvatski (Bosna i Hercegovina)",

    /* Day Name Strings */
    dayNames: ["nedjelja", "ponedjeljak", "utorak", "srijeda", "četvrtak", "petak", "subota"],
    abbreviatedDayNames: ["ned", "pon", "uto", "sri", "čet", "pet", "sub"],
    shortestDayNames: ["ned", "pon", "uto", "sri", "čet", "pet", "sub"],
    firstLetterDayNames: ["n", "p", "u", "s", "č", "p", "s"],

    /* Month Name Strings */
    monthNames: ["siječanj", "veljača", "ožujak", "travanj", "svibanj", "lipanj", "srpanj", "kolovoz", "rujan", "listopad", "studeni", "prosinac"],
    abbreviatedMonthNames: ["sij", "vlj", "ožu", "tra", "svi", "lip", "srp", "kol", "ruj", "lis", "stu", "pro"],

	/* AM/PM Designators */
    amDesignator: "",
    pmDesignator: "",

    firstDayOfWeek: 1,
    twoDigitYearMax: 2029,

    /**
     * The dateElementOrder is based on the order of the
     * format specifiers in the formatPatterns.DatePattern.
     *
     * Example:
     <pre>
     shortDatePattern    dateElementOrder
     ------------------  ----------------
     "M/d/yyyy"          "mdy"
     "dd/MM/yyyy"        "dmy"
     "yyyy-MM-dd"        "ymd"
     </pre>
     * The correct dateElementOrder is required by the parser to
     * determine the expected order of the date elements in the
     * string being parsed.
     *
     * NOTE: It is VERY important this value be correct for each Culture.
     */
    dateElementOrder: "dmy",

    /* Standard date and time format patterns */
    formatPatterns: {
        shortDate: "d.M.yyyy",
        longDate: "d. MMMM yyyy",
        shortTime: "H:mm:ss",
        longTime: "H:mm:ss",
        fullDateTime: "d. MMMM yyyy H:mm:ss",
        sortableDateTime: "yyyy-MM-ddTHH:mm:ss",
        universalSortableDateTime: "yyyy-MM-dd HH:mm:ssZ",
        rfc1123: "ddd, dd MMM yyyy HH:mm:ss GMT",
        monthDay: "MMMM dd",
        yearMonth: "MMMM, yyyy"
    },

    /**
     * NOTE: If a string format is not parsing correctly, but
     * you would expect it parse, the problem likely lies below.
     *
     * The following regex patterns control most of the string matching
     * within the parser.
     *
     * The Month name and Day name patterns were automatically generated
     * and in general should be (mostly) correct.
     *
     * Beyond the month and day name patterns are natural language strings.
     * Example: "next", "today", "months"
     *
     * These natural language string may NOT be correct for this culture.
     * If they are not correct, please translate and edit this file
     * providing the correct regular expression pattern.
     *
     * If you modify this file, please post your revised CultureInfo file
     * to the Datejs Discussions located at
     *     http://groups.google.com/group/date-js
     *
     * Please mark the subject with [CultureInfo]. Example:
     *    Subject: [CultureInfo] Translated "da-DK" Danish(Denmark)
     *
     * We will add the modified patterns to the master source files.
     *
     * As well, please review the list of "Future Strings" section below.
     */
    regexPatterns: {
        jan: /^sij(ečanj)?/i,
        feb: /^veljača/i,
        mar: /^ožu(jak)?/i,
        apr: /^tra(vanj)?/i,
        may: /^svi(banj)?/i,
        jun: /^lip(anj)?/i,
        jul: /^srp(anj)?/i,
        aug: /^kol(ovoz)?/i,
        sep: /^ruj(an)?/i,
        oct: /^lis(topad)?/i,
        nov: /^stu(deni)?/i,
        dec: /^pro(sinac)?/i,

        sun: /^nedjelja/i,
        mon: /^ponedjeljak/i,
        tue: /^utorak/i,
        wed: /^srijeda/i,
        thu: /^četvrtak/i,
        fri: /^petak/i,
        sat: /^subota/i,

        future: /^next/i,
        past: /^last|past|prev(ious)?/i,
        add: /^(\+|after|from)/i,
        subtract: /^(\-|before|ago)/i,

        yesterday: /^yesterday/i,
        today: /^t(oday)?/i,
        tomorrow: /^tomorrow/i,
        now: /^n(ow)?/i,

        millisecond: /^ms|milli(second)?s?/i,
        second: /^sec(ond)?s?/i,
        minute: /^min(ute)?s?/i,
        hour: /^h(ou)?rs?/i,
        week: /^w(ee)?k/i,
        month: /^m(o(nth)?s?)?/i,
        day: /^d(ays?)?/i,
        year: /^y((ea)?rs?)?/i,

        shortMeridian: /^(a|p)/i,
        longMeridian: /^(a\.?m?\.?|p\.?m?\.?)/i,
        timezone: /^((e(s|d)t|c(s|d)t|m(s|d)t|p(s|d)t)|((gmt)?\s*(\+|\-)\s*\d\d\d\d?)|gmt)/i,
        ordinalSuffix: /^\s*(st|nd|rd|th)/i,
        timeContext: /^\s*(\:|a|p)/i
    },

    abbreviatedTimeZoneStandard: { GMT: "-000", EST: "-0400", CST: "-0500", MST: "-0600", PST: "-0700" },
    abbreviatedTimeZoneDST: { GMT: "-000", EDT: "-0500", CDT: "-0600", MDT: "-0700", PDT: "-0800" }

};

/********************
 ** Future Strings **
 ********************
 *
 * The following list of strings are not currently being used, but
 * may be incorporated later. We would appreciate any help translating
 * the strings below.
 *
 * If you modify this file, please post your revised CultureInfo file
 * to the Datejs Discussions located at
 *     http://groups.google.com/group/date-js
 *
 * Please mark the subject with [CultureInfo]. Example:
 *    Subject: [CultureInfo] Translated "da-DK" Danish(Denmark)
 *
 * English Name        Translated
 * ------------------  -----------------
 * date                date
 * time                time
 * calendar            calendar
 * show                show
 * hourly              hourly
 * daily               daily
 * weekly              weekly
 * bi-weekly           bi-weekly
 * monthly             monthly
 * bi-monthly          bi-monthly
 * quarter             quarter
 * quarterly           quarterly
 * yearly              yearly
 * annual              annual
 * annually            annually
 * annum               annum
 * again               again
 * between             between
 * after               after
 * from now            from now
 * repeat              repeat
 * times               times
 * per                 per
 */


text:
* glance: Add Support for Image Service API v2

# 3.2.8 / 2020-01-29
* jackson upgraded to com.fasterxml version 2.9.x
* commons-httpclient upgraded to org.apache.httpcomponents 4.5

# 3.2.7 / 2019-05-03
* Remove maven-gpg-plugin

# 3.2.6 / 2019-05-03
* RESTEasyConnector: Support RESTEasy 3.6.3.Final

# 3.2.5 / 2018-11-14
* neutron: Add support for `port_security_enabled` on Networks

# 3.2.4 / 2018
* Improved backward compatibility to 3.1.3

# 3.2.3 / 2018-06-24
* No user visible changes

# 3.2.2 / 2018-06-23
* Add keystone v3 support
* Add missing nova utility methods for server actions
* Add heat support
* Add router support
* All fixes and improvements up to 3.1.3

# 3.1.3 / 2018-05-18
* Cinder: Add support for `os-terminate_connection`
* neutron: Support parameter mtu

# 3.1.2 / 2017-01-28
* RESTEasyConnector: Isolate the creation of ClientExecutor

# 3.1.1 / 2015-05-06
* cinder: introduce client and model
* java 7
* Fixes and improvements up to 3.0.6

# 3.2.1 / 2013-07-26
* No user visible changes

# 3.2.0 / 2013-07-26
* support quota/limits/usage operations
* logging enhancements

# 3.1.0 / 2013-07-21


text:
export declare const DEFAULT_LOCALE = 'en-US';
export declare const PSEUDO_LOCALE = 'en-ZZ';
export declare const RUNTIME: {
  locale: string;
  defaultLocale: string;
  instances: Set<any>;
  padRatio: number;
};
declare function setLocale(locale: any): Promise<void>;
export default class I18n {
  _loadLocale: any;
  _cache: any;
  constructor(loadLocale: any);
  _load(locale: any): Promise<void>;
  load(): Promise<void>;
  _getString(key: any, locale: any): any;
  getString(key: any, locale?: string): any;
  readonly currentLocale: string;
  static readonly setLocale: typeof setLocale;
}
export {};