text:
//-----------------------------------------------------------------------
// <copyright file="SchemaBuilder.cs" company="madd0.com">
//     Copyright (c) 2012 Mauricio DIAZ ORLICH.
//     Code licensed under the MIT X11 license.
// </copyright>
// <author>Mauricio DIAZ ORLICH</author>
//-----------------------------------------------------------------------
namespace Madd0.AzureStorageDriver
{
#if NETCORE
    using Microsoft.Azure.Cosmos.Table;
#else
    using Microsoft.Azure.CosmosDB.Table;
#endif

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Net;
    using System.Reflection;
    using System.Threading.Tasks;
    using LINQPad.Extensibility.DataContext;
    using Madd0.AzureStorageDriver.Properties;

    /// <summary>
    /// Provides the methods necessary to determining the storage account's schema and to building
    /// the typed data context .
    /// </summary>
    internal static class SchemaBuilder
    {
        // Names of columns that should be marked as table keys.
        private static readonly List<string> KeyColumns = new List<string> { "PartitionKey", "RowKey" };

        /// <summary>
        /// Gets the schema and builds the assembly.
        /// </summary>
        /// <param name="properties">The current configuration.</param>
        /// <param name="name">The <see cref="AssemblyName"/> instace of the assembly being created.</param>
        /// <param name="namepace">The namespace to be used in the generated code.</param>
        /// <param name="typeName">Name of the type of the typed data context.</param>
        /// <returns>A list of <see cref="ExplorerItem"/> instaces that describes the current schema.</returns>
        public static List<ExplorerItem> GetSchemaAndBuildAssembly(StorageAccountProperties properties, AssemblyName name, string @namepace, string typeName)
        {
            // Get the model from Azure storage
            var model = GetModel(properties);

            // Generate C# code
            var code = GenerateCode(typeName, @namepace, model);

            // And compile the code into the assembly
            BuildAssembly(name, code);

            // Generate the schema for LINQPad
            List<ExplorerItem> schema = GetSchema(model);

            return schema;
        }

        /// <summary>
        /// Build a model of the current Azure storage account. This model will be used to generate
        /// the typed code as well as the schema needed by LINQPad.
        /// </summary>
        /// <param name="properties">The current configuration.</param>
        /// <returns>A list of <see cref="CloudTable"/> instances that describe the current Azure
        /// storage model.</returns>
        private static IEnumerable<CloudTable> GetModel(StorageAccountProperties properties)
        {
            // make sure that we can make at least ModelLoadMaxParallelism concurrent
            // cals to azure table storage
            ServicePointManager.DefaultConnectionLimit = properties.ModelLoadMaxParallelism;

            var tableClient = properties.GetStorageAccount().CreateCloudTableClient();

            // First get a list of all tables
            var model = (from tableName in tableClient.ListTables()
                         select new CloudTable
                         {
                             Name = tableName.Name
                         }).ToList();

            var options = new ParallelOptions()
            {
                MaxDegreeOfParallelism = properties.ModelLoadMaxParallelism
            };

            Parallel.ForEach(model, options, table =>
            {
                var threadTableClient = properties.GetStorageAccount().CreateCloudTableClient();

                var tableColumns = threadTableClient.GetTableReference(table.Name).ExecuteQuery(new TableQuery().Take(properties.NumberOfRows))
                    .SelectMany(row => row.Properties)
                    .GroupBy(column => column.Key)
                    .Select(grp => new TableColumn
                    {
                        Name = grp.Key,
                        TypeName = GetType(grp.First().Value.PropertyType)
                    });

                var baseColumns = new List<TableColumn>
                {
                    new TableColumn { Name = "PartitionKey", TypeName = GetType(EdmType.String) },
                    new TableColumn { Name = "RowKey", TypeName = GetType(EdmType.String) },
                    new TableColumn { Name = "Timestamp", TypeName = GetType(EdmType.DateTime) },
                    new TableColumn { Name = "ETag", TypeName = GetType(EdmType.String) }
                };

                table.Columns = tableColumns.Concat(baseColumns).ToArray();
            });

            return model;
        }

        /// <summary>
        /// Generates the code to build the typed data context.
        /// </summary>
        /// <param name="typeName">Name of the type.</param>
        /// <param name="namespace">The namespace.</param>
        /// <param name="model">The model.</param>
        /// <returns>The code to be compiled as a string.</returns>
        private static string GenerateCode(string typeName, string @namespace, IEnumerable<CloudTable> model)
        {
            // We use a T4-generated class as the template
            var codeGenerator = new DataContextTemplate
            {
                Namespace = @namespace,
                TypeName = typeName,
                Tables = model
            };

            // As a workaround for compiling issues when referencing the driver DLL itself to
            // access the base ExtendedTableQuery class, the code will be used instead in the
            // dynamic assembly.
            var baseClass = ReadEmbeddedBaseClassCode();

            var sourceCode = baseClass + codeGenerator.TransformText();
            LINQPad.Util.Break();

            return sourceCode;
        }

        private static string ReadEmbeddedBaseClassCode()
        {
            var assembly = Assembly.GetExecutingAssembly();
            var resourceName = "Madd0.AzureStorageDriver.ExtendedTableQuery.cs";

            using var reader = new StreamReader(assembly.GetManifestResourceStream(resourceName));

            return reader.ReadToEnd();
        }

        /// <summary>
        /// Builds the assembly described by the <see cref="AssemblyName"/>.
        /// </summary>
        /// <param name="name">The <see cref="AssemblyName"/> instace of the assembly being created.</param>
        /// <param name="code">The code of the typed data context.</param>
        private static void BuildAssembly(AssemblyName name, string code)
        {
            ICompiler compiler;

            var dependencies = new List<string>
            {
                typeof(TableQuery).Assembly.Location
            };
#if NETCORE
            compiler = new RoslynCompiler();
#else
            compiler = new CodeDomCompiler();
            dependencies.Add("System.dll");
            dependencies.Add("System.Core.dll");
            dependencies.Add("System.Xml.dll");
            dependencies.Add(typeof(Microsoft.Azure.Storage.OperationContext).Assembly.Location);
#endif
            compiler.Compile(code, name, dependencies);
        }

        /// <summary>
        /// Transforms the model based on <see cref="CloudTable"/> instances into a schema based on
        /// <see cref="ExplorerItem"/> instances for LINQPad.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <returns>A schema for LINQPad.</returns>
        private static List<ExplorerItem> GetSchema(IEnumerable<CloudTable> model)
        {
            return (from table in model
                    select new ExplorerItem(table.Name, ExplorerItemKind.QueryableObject, ExplorerIcon.Table)
                    {
                        Children = (from column in table.Columns
                                    select new ExplorerItem(column.Name + " (" + column.TypeName + ")", ExplorerItemKind.Property, ExplorerIcon.Column)
                                    {
                                        Icon = KeyColumns.Contains(column.Name) ? ExplorerIcon.Key : ExplorerIcon.Column,
                                        DragText = column.Name
                                    }).ToList(),
                        DragText = table.Name,
                        IsEnumerable = true
                    }).ToList();
        }

        /// <summary>
        /// Gets the C# type equivalent of an entity data model (Edm) type.
        /// </summary>
        /// <param name="type">The Edm type.</param>
        /// <returns>The C# type.</returns>
        private static string GetType(EdmType type)
        {
            return type switch
            {
                EdmType.Binary => "byte[]",

                EdmType.Boolean => "bool?",

                EdmType.DateTime => "DateTime?",

                EdmType.Double => "double?",

                EdmType.Guid => "Guid?",

                EdmType.Int32 => "int?",

                EdmType.Int64 => "long?",

                EdmType.String => "string",

                _ => throw new NotSupportedException(string.Format(Exceptions.TypeNotSupported, type)),
            };
        }
    }
}


text:
"format cjs";

// TODO: cleanup removing package.json
var utils = require('./npm-utils');
var crawl = require('./npm-crawl');

// Add @loader, for SystemJS
if(!System.has("@loader")) {
	System.set('@loader', System.newModule({'default':System, __useDefault: true}));
}

// SYSTEMJS PLUGIN EXPORTS =================

/**
 * @function translate
 * @description Convert the package.json file into a System.config call.
 * @signature `translate(load)`
 * @param {Object} load Load object
 * @return {Promise} a promise to resolve with the load's new source.
 */
exports.translate = function(load){
	var loader = this;

	// This could be an empty string if the fetch failed.
	if(load.source == "") {
		return "define([]);";
	}

	var context = {
		packages: [],
		loader: this,
		// places we
		paths: {},
		versions: {}
	};
	var pkg = {origFileUrl: load.address, fileUrl: load.address};

	crawl.processPkgSource(context, pkg, load.source);

	return crawl.deps(context, pkg, true).then(function(){
		// clean up packages so everything is unique
		var names = {};
		var packages = [];
		utils.forEach(context.packages, function(pkg, index){
			if(!packages[pkg.name+"@"+pkg.version]) {
				if(pkg.browser){
					delete pkg.browser.transform;
				}
				packages.push({
					name: pkg.name,
					version: pkg.version,
					fileUrl: pkg.fileUrl,
					main: pkg.main,
					system: convertSystem(context, pkg, pkg.system, index === 0 ),
					globalBrowser: convertBrowser( pkg, pkg.globalBrowser ),
					browser: convertBrowser( pkg,  pkg.browser )
				});
				packages[pkg.name+"@"+pkg.version] = true;
			}
		});
		var configDependencies = ['@loader','npm-extension'].concat(configDeps.call(loader, pkg));
		var pkgMain = utils.pkg.hasDirectoriesLib(pkg) ?
			convertName(context, pkg, false, true, pkg.name+"/"+utils.pkg.main(pkg)) :
			utils.pkg.main(pkg);

		return "define("+JSON.stringify(configDependencies)+", function(loader, npmExtension){\n" +
			"npmExtension.addExtension(loader);\n"+
		    (pkg.main ? "if(!loader.main){ loader.main = "+JSON.stringify(pkgMain)+"; }\n" : "") +
			"loader._npmExtensions = [].slice.call(arguments, 2);\n" +
			"("+translateConfig.toString()+")(loader, "+JSON.stringify(packages, null, " ")+");\n" +
		"});";
	});
};

// Translate helpers ===============
// Given all the package.json data, these helpers help convert it to a source.
function convertSystem(context, pkg, system, root) {
	if(!system) {
		return system;
	}
	if(system.meta) {
		system.meta = convertPropertyNames(context, pkg, system.meta, root);
	}
	if(system.map) {
		system.map = convertPropertyNamesAndValues(context, pkg, system.map, root);
	}
	if(system.paths) {
		system.paths = convertPropertyNames(context, pkg, system.paths, root);
	}
	// needed for builds
	if(system.buildConfig) {
		system.buildConfig = convertSystem(context, pkg, system.buildConfig, root);
	}
	return system;
}

// converts only the property name
function convertPropertyNames (context, pkg, map , root) {
	if(!map) {
		return map;
	}
	var clone = {};
	for(var property in map ) {
		clone[convertName(context, pkg, map, root, property)] = map[property];
		// do root paths b/c we don't know if they are going to be included with the package name or not.
		if(root) {
			clone[convertName(context, pkg, map, false, property)] = map[property];
		}
	}
	return clone;
}

// converts both property name and value
function convertPropertyNamesAndValues (context, pkg, map , root) {
	if(!map) {
		return map;
	}
	var clone = {}, val;
	for(var property in map ) {
		val = map[property];
		clone[convertName(context, pkg, map, root, property)] = typeof val === "object"
			? convertPropertyNamesAndValues(context, pkg, val, root)
			: convertName(context, pkg, map, root, val);
	}
	return clone;
}

function convertName (context, pkg, map, root, name) {
	var parsed = utils.moduleName.parse(name, pkg.name),
		depPkg, requestedVersion;
	if( name.indexOf("#") >= 0 ) {

		if(parsed.packageName === pkg.name) {
			parsed.version = pkg.version;
		} else {
			// Get the requested version's actual version.
			requestedVersion = crawl.getDependencyMap(context.loader, pkg, root)[parsed.packageName].version;
			depPkg = context.versions[parsed.packageName][requestedVersion];
			parsed.version = depPkg.version;
		}
		return utils.moduleName.create(parsed);

	} else {
		if(root && name.substr(0,2) === "./" ) {
			return name.substr(2);
		} else {
			// this is for a module within the package
			if (name.substr(0,2) === "./" ) {
				return utils.moduleName.create({
					packageName: pkg.name,
					modulePath: name,
					version: pkg.version,
					plugin: parsed.plugin
				});
			} else {
				// TODO: share code better!
				// SYSTEM.NAME
				if(  pkg.name === parsed.packageName || ( (pkg.system && pkg.system.name) === parsed.packageName) ) {
					depPkg = pkg;
				} else {
					var requestedProject = crawl.getDependencyMap(context.loader, pkg, root)[parsed.packageName];
					if(!requestedProject) {
						warn(name);
						return name;
					}
					requestedVersion = requestedProject.version;
					depPkg = crawl.matchedVersion(context, parsed.packageName, requestedVersion);
					// If we still didn't find one just use the first available version.
					if(!depPkg) {
						var versions = context.versions[parsed.packageName];
						depPkg = versions && versions[requestedVersion];
					}
				}
				// SYSTEM.NAME
				if(depPkg.system && depPkg.system.name) {
					parsed.packageName = depPkg.system.name;
				}

				parsed.version = depPkg.version;
				if(!parsed.modulePath) {
					parsed.modulePath = utils.pkg.main(depPkg);
				}
				return utils.moduleName.create(parsed);
			}

		}

	}
}

/**
 * Converts browser names into actual module names.
 *
 * Example:
 *
 * ```
 * {
 * 	 "foo": "browser-foo"
 *   "traceur#src/node/traceur": "./browser/traceur"
 *   "./foo" : "./foo-browser"
 * }
 * ```
 *
 * converted to:
 *
 * ```
 * {
 * 	 // any foo ... regardless of where
 *   "foo": "browser-foo"
 *   // this module ... ideally minus version
 *   "traceur#src/node/traceur": "transpile#./browser/traceur"
 *   "transpile#./foo" : "transpile#./foo-browser"
 * }
 * ```
 */
function convertBrowser(pkg, browser) {
	if(typeof browser === "string") {
		return browser;
	}
	var map = {};
	for(var fromName in browser) {
		convertBrowserProperty(map, pkg, fromName, browser[fromName]);
	}
	return map;
}

function convertBrowserProperty(map, pkg, fromName, toName) {
	var packageName = pkg.name;

	var fromParsed = utils.moduleName.parse(fromName, packageName),
		  toParsed = toName  ? utils.moduleName.parse(toName, packageName): "@empty";

	map[utils.moduleName.create(fromParsed)] = utils.moduleName.create(toParsed);
}

// Dependencies from a package.json file specified in `system.configDependencies`
function configDeps(pkg) {
	var deps = [];
	if(pkg.system && pkg.system.configDependencies) {
		deps = deps.concat(pkg.system.configDependencies);
	}
	if(this.configDependencies) {
		deps = deps.concat(this.configDependencies);
	}
	return deps;
}

var translateConfig = function(loader, packages){
	var g;
	if(typeof window !== "undefined") {
		g = window;
	} else {
		g = global;
	}
	if(!g.process) {
		g.process = {
			cwd: function(){},
			env: {
				NODE_ENV: loader.env
			}
		};
	}

	if(!loader.npm) {
		loader.npm = {};
		loader.npmPaths = {};
		loader.globalBrowser = {};
	}
	loader.npmPaths.__default = packages[0];
	var lib = packages[0].system && packages[0].system.directories && packages[0].system.directories.lib;

	var setGlobalBrowser = function(globals, pkg){
		for(var name in globals) {
			loader.globalBrowser[name] = {
				pkg: pkg,
				moduleName: globals[name]
			};
		}
	};
	var setInNpm = function(name, pkg){
		if(!loader.npm[name]) {
			loader.npm[name] = pkg;
		}
		loader.npm[name+"@"+pkg.version] = pkg;
	};
	var forEach = function(arr, fn){
		var i = 0, len = arr.length;
		for(; i < len; i++) {
			fn.call(arr, arr[i]);
		}
	};
	forEach(packages, function(pkg){
		if(pkg.system) {
			// don't set system.main
			var main = pkg.system.main;
			delete pkg.system.main;
			loader.config(pkg.system);
			pkg.system.main = main;

		}
		if(pkg.globalBrowser) {
			setGlobalBrowser(pkg.globalBrowser, pkg);
		}
		var systemName = pkg.system && pkg.system.name;
		if(systemName) {
			setInNpm(systemName, pkg);
		} else {
			setInNpm(pkg.name, pkg);
		}
		if(!loader.npm[pkg.name]) {
			loader.npm[pkg.name] = pkg;
		}
		loader.npm[pkg.name+"@"+pkg.version] = pkg;
		var pkgAddress = pkg.fileUrl.replace(/\/package\.json.*/,"");
		loader.npmPaths[pkgAddress] = pkg;
	});
	forEach(loader._npmExtensions || [], function(ext){
		// If there is a systemConfig use that as configuration
		if(ext.systemConfig) {
			loader.config(ext.systemConfig);
		}
	});
};

var warn = (function(){
	var warned = {};
	return function(name){
		if(false /*!warned[name]*/) {
			warned[name] = true;
			var warning = "WARN: Could not find " + name + " in node_modules. Ignoring.";
			if(typeof steal !== "undefined" && steal.dev) steal.dev.warn(warning)
			else if(console.warn) console.warn(warning);
			else console.log(warning);
		}
	};
})();

redpajama_set_name: RedPajamaGithub


text:
package org.zaproxy.zap.extension.httpsessions;

import java.awt.Component;
import org.parosproxy.paros.Constant;
import org.parosproxy.paros.extension.ExtensionPopupMenuItem;

/**
 * The PopupMenuUnsetActiveSession is used to unset the active http session for the {@link
 * ExtensionHttpSessions}.
 */
@SuppressWarnings("serial")
public class PopupMenuUnsetActiveSession extends ExtensionPopupMenuItem {

    /** The Constant serialVersionUID. */
    private static final long serialVersionUID = 1L;

    /** The extension. */
    private ExtensionHttpSessions extension;

    /** Instantiates a new popup menu used to unset active session. */
    public PopupMenuUnsetActiveSession() {
        super(Constant.messages.getString("httpsessions.popup.session.active.unset"));
        initialize();
    }

    /**
     * Sets the extension.
     *
     * @param extension the new extension
     */
    public void setExtension(ExtensionHttpSessions extension) {
        this.extension = extension;
    }

    /** Initialize the popup menu. */
    private void initialize() {
        this.addActionListener(
                new java.awt.event.ActionListener() {
                    @Override
                    public void actionPerformed(java.awt.event.ActionEvent e) {
                        // Get the HttpSessionsSite
                        HttpSessionsPanel panel = extension.getHttpSessionsPanel();
                        HttpSessionsSite site = panel.getCurrentHttpSessionSite();
                        if (site == null) return;

                        // Unset the active session, no matter the current selection is, as the
                        // popup menu
                        // is always only enabled on active session
                        site.unsetActiveSession();
                    }
                });
    }

    @Override
    public boolean isEnableForComponent(Component invoker) {
        // Only enable it for the HttpSessionsPanel and for the entries that are not already active
        if (invoker.getName() != null && invoker.getName().equals(HttpSessionsPanel.PANEL_NAME)) {
            HttpSession item = extension.getHttpSessionsPanel().getSelectedSession();
            if (item != null) {
                if (item.isActive()) return true;
                else return false;
            }
        }
        return false;
    }

    @Override
    public boolean isSafe() {
        return true;
    }
}


text:
package org.apache.geode.internal.cache.ha;

import static org.apache.geode.distributed.ConfigurationProperties.LOCATORS;
import static org.apache.geode.distributed.ConfigurationProperties.MCAST_PORT;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;

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

import org.junit.Ignore;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import org.apache.geode.cache.AttributesFactory;
import org.apache.geode.cache.Cache;
import org.apache.geode.cache.CacheException;
import org.apache.geode.cache.CacheFactory;
import org.apache.geode.cache.CacheListener;
import org.apache.geode.cache.DataPolicy;
import org.apache.geode.cache.EntryEvent;
import org.apache.geode.cache.InterestResultPolicy;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.RegionAttributes;
import org.apache.geode.cache.Scope;
import org.apache.geode.cache.util.CacheListenerAdapter;
import org.apache.geode.cache30.CacheSerializableRunnable;
import org.apache.geode.cache30.ClientServerTestCase;
import org.apache.geode.distributed.DistributedSystem;
import org.apache.geode.internal.AvailablePort;
import org.apache.geode.internal.cache.CacheServerImpl;
import org.apache.geode.test.dunit.Host;
import org.apache.geode.test.dunit.IgnoredException;
import org.apache.geode.test.dunit.NetworkUtils;
import org.apache.geode.test.dunit.VM;
import org.apache.geode.test.dunit.internal.JUnit4DistributedTestCase;
import org.apache.geode.test.junit.categories.ClientSubscriptionTest;

/**
 * This is the Dunit test to verify the duplicates after the fail over The test perorms following
 * operations 1. Create 2 servers and 1 client 2. Perform put operations for knows set of keys
 * directy from the server1. 3. Stop the server1 so that fail over happens 4. Validate the
 * duplicates received by the client1
 */
@Category({ClientSubscriptionTest.class})
public class HADuplicateDUnitTest extends JUnit4DistributedTestCase {

  VM server1 = null;

  VM server2 = null;

  VM client1 = null;

  VM client2 = null;

  private static final String REGION_NAME = "HADuplicateDUnitTest_Region";

  protected static Cache cache = null;

  static boolean isEventDuplicate = true;

  static CacheServerImpl server = null;

  static final int NO_OF_PUTS = 100;

  public static final Object dummyObj = "dummyObject";

  static boolean waitFlag = true;

  static int put_counter = 0;

  static Map storeEvents = new HashMap();

  @Override
  public final void postSetUp() throws Exception {
    final Host host = Host.getHost(0);

    server1 = host.getVM(0);

    server2 = host.getVM(1);

    client1 = host.getVM(2);

    client2 = host.getVM(3);
  }

  @Override
  public final void preTearDown() throws Exception {
    client1.invoke(() -> HADuplicateDUnitTest.closeCache());
    // close server
    server1.invoke(() -> HADuplicateDUnitTest.reSetQRMslow());
    server1.invoke(() -> HADuplicateDUnitTest.closeCache());
    server2.invoke(() -> HADuplicateDUnitTest.closeCache());
  }

  @Ignore("TODO")
  @Test
  public void testDuplicate() throws Exception {
    createClientServerConfiguration();
    server1.invoke(putForKnownKeys());
    server1.invoke(stopServer());

    // wait till all the duplicates are received by client
    client1.invoke(new CacheSerializableRunnable("waitForPutToComplete") {

      @Override
      public void run2() throws CacheException {
        synchronized (dummyObj) {
          while (waitFlag) {
            try {
              dummyObj.wait();
            } catch (InterruptedException e) {
              fail("interrupted");
            }
          }
        }

        if (waitFlag)
          fail("test failed");
      }
    });

    // validate the duplicates received by client
    client1.invoke(new CacheSerializableRunnable("validateDuplicates") {
      @Override
      public void run2() throws CacheException {
        if (!isEventDuplicate)
          fail(" Not all duplicates received");

      }
    });

    server1.invoke(() -> HADuplicateDUnitTest.reSetQRMslow());
  }

  @Test
  public void testSample() throws Exception {
    IgnoredException.addIgnoredException("IOException");
    IgnoredException.addIgnoredException("Connection reset");
    createClientServerConfiguration();
    server1.invoke(new CacheSerializableRunnable("putKey") {

      @Override
      public void run2() throws CacheException {
        Region region = cache.getRegion(Region.SEPARATOR + REGION_NAME);
        assertNotNull(region);
        region.put("key1", "value1");

      }
    });
  }

  // function to perform put operations for the known set of keys.
  private CacheSerializableRunnable putForKnownKeys() {

    CacheSerializableRunnable putforknownkeys = new CacheSerializableRunnable("putforknownkeys") {

      @Override
      public void run2() throws CacheException {
        Region region = cache.getRegion(Region.SEPARATOR + REGION_NAME);
        assertNotNull(region);
        for (int i = 0; i < NO_OF_PUTS; i++) {
          region.put("key" + i, "value" + i);
        }
      }

    };

    return putforknownkeys;
  }

  // function to stop server so that the fail over happens
  private CacheSerializableRunnable stopServer() {

    CacheSerializableRunnable stopserver = new CacheSerializableRunnable("stopServer") {
      @Override
      public void run2() throws CacheException {
        server.stop();
      }

    };

    return stopserver;
  }

  // function to create 2servers and 1 clients
  private void createClientServerConfiguration() {
    int PORT1 =
        ((Integer) server1.invoke(() -> HADuplicateDUnitTest.createServerCache())).intValue();
    server1.invoke(() -> HADuplicateDUnitTest.setQRMslow());
    int PORT2 =
        ((Integer) server2.invoke(() -> HADuplicateDUnitTest.createServerCache())).intValue();
    String hostname = NetworkUtils.getServerHostName(Host.getHost(0));
    client1.invoke(() -> HADuplicateDUnitTest.createClientCache(hostname, new Integer(PORT1),
        new Integer(PORT2)));

  }

  // function to set QRM slow
  public static void setQRMslow() {
    System.setProperty("QueueRemovalThreadWaitTime", "100000");
  }

  public static void reSetQRMslow() {
    System.setProperty("QueueRemovalThreadWaitTime", "1000");
  }

  public static Integer createServerCache() throws Exception {
    new HADuplicateDUnitTest().createCache(new Properties());
    AttributesFactory factory = new AttributesFactory();
    factory.setScope(Scope.DISTRIBUTED_ACK);
    factory.setDataPolicy(DataPolicy.REPLICATE);
    RegionAttributes attrs = factory.create();
    cache.createRegion(REGION_NAME, attrs);
    server = (CacheServerImpl) cache.addCacheServer();
    assertNotNull(server);
    int port = AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET);
    server.setPort(port);
    server.setNotifyBySubscription(true);
    server.start();
    return new Integer(server.getPort());
  }

  private void createCache(Properties props) throws Exception {
    DistributedSystem ds = getSystem(props);
    assertNotNull(ds);
    ds.disconnect();
    ds = getSystem(props);
    cache = CacheFactory.create(ds);
    assertNotNull(cache);
  }

  public static void createClientCache(String hostName, Integer port1, Integer port2)
      throws Exception {
    int PORT1 = port1.intValue();
    int PORT2 = port2.intValue();
    Properties props = new Properties();
    props.setProperty(MCAST_PORT, "0");
    props.setProperty(LOCATORS, "");
    new HADuplicateDUnitTest().createCache(props);
    AttributesFactory factory = new AttributesFactory();
    ClientServerTestCase.configureConnectionPool(factory, hostName, new int[] {PORT1, PORT2}, true,
        -1, 2, null);

    factory.setScope(Scope.DISTRIBUTED_ACK);
    CacheListener clientListener = new HAValidateDuplicateListener();
    factory.setCacheListener(clientListener);

    RegionAttributes attrs = factory.create();
    cache.createRegion(REGION_NAME, attrs);
    Region region = cache.getRegion(Region.SEPARATOR + REGION_NAME);
    assertNotNull(region);
    region.registerInterest("ALL_KEYS", InterestResultPolicy.NONE);

  }

  public static void closeCache() {
    if (cache != null && !cache.isClosed()) {
      cache.close();
      cache.getDistributedSystem().disconnect();
    }
  }
}

// TODO: move these classes to be inner static classes

// Listener class for the validation purpose
class HAValidateDuplicateListener extends CacheListenerAdapter {
  @Override
  public void afterCreate(EntryEvent event) {
    System.out.println("After Create");
    HADuplicateDUnitTest.storeEvents.put(event.getKey(), event.getNewValue());
  }

  @Override
  public void afterUpdate(EntryEvent event) {
    Object value = HADuplicateDUnitTest.storeEvents.get(event.getKey());
    if (value == null)
      HADuplicateDUnitTest.isEventDuplicate = false;
    synchronized (HADuplicateDUnitTest.dummyObj) {
      try {
        HADuplicateDUnitTest.put_counter++;
        if (HADuplicateDUnitTest.put_counter == HADuplicateDUnitTest.NO_OF_PUTS) {
          HADuplicateDUnitTest.waitFlag = false;
          HADuplicateDUnitTest.dummyObj.notifyAll();
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
    }

  }
}


text:
  Labastidette est
      une ville géographiquement positionnée dans le département de Haute-Garonne en Midi-Pyrénées. Elle totalisait 1 785 habitants en 2008.

Le nombre d'habitations, à Labastidette, se décomposait en 2011 en 170 appartements et 702 maisons soit
 un marché relativement équilibré.

La commune offre quelques  équipements, elle propose entre autres un terrain de tennis, un terrain de sport et une salle de combat.

À Labastidette, la valorisation moyenne à l'achat d'un appartement se situe à 2 185 € du m² en vente. La valeur moyenne d'une maison à l'achat se situe à 2 469 € du m². À la location la valeur moyenne se situe à 9,23 € du m² par mois.

À Labastidette le salaire moyen mensuel par personne est situé à approximativement 2 113 €  net. Ceci est équivalent à la moyenne du pays.

À proximité de Labastidette sont situées les villes de
Poucharramet à 7 km, 795 habitants,
Saint-Hilaire localisée à 4 km, 932 habitants,
Muret à 6 km, 23 622 habitants,
Cambernard localisée à 5 km, 428 habitants,
Lamasquère à 2 km, 1 108 habitants,
Lherm localisée à 3 km, 3 117 habitants,
 entre autres. De plus, Labastidette est située à seulement 22 km de Toulouse.


text:
enum BOOLOPERATION { AND=0, OR=1, XOR=2 };                                      // The three possible boolean operations. Boolean Difference can be acomplished with AND and negative area.

inline int sign(GLdouble x) { return (x > 0)?( 1 ):( (x < 0)?( -1 ):( 0 ) ); }  // Returns the sign of a number (e.g. -1 for -2, +1 for 3). Zero returns zero.

inline GLdouble max(GLdouble x, GLdouble y) { return (x > y)?(x):(y); }         // Maximum of two `GLdouble`s.
inline GLdouble min(GLdouble x, GLdouble y) { return (x < y)?(x):(y); }         // Minimum of two `GLdouble`s.

bool getRoot(GLdouble* root, GLdouble a, GLdouble b, GLdouble c, GLdouble s=1); // Sets the value at the pointer `root` to be the right root (`s > 0`), left root (`s < 0`), or center (`s == 0`) of a parabola `y = ax^2 + bx = c`.

#endif


text:
#include "node.h"

/**************************************************************************************************************/

/*Constructs the node object*/
Node::Node(int nodeXIndex, int nodeYIndex)
{
	/*initialise the booleans*/
	startNode = false;
	endNode = false;
	listed = false;
	safe = true;

	/*initialise the variables*/
	this->nodeXIndex = nodeXIndex;
	this->nodeYIndex = nodeYIndex;
	parentNodeXIndex = 0;
	parentNodeYIndex = 0;
	cost = 0;
	fScore = 0;
}

/**************************************************************************************************************/

/*Destructs the node object*/
Node::~Node()
{
}

/**************************************************************************************************************/

/*set the parent node index*/
void Node::setParentIndex(int parentNodeXIndex, int parentNodeYIndex)
{
	/*set the variables to the input*/
	this->parentNodeXIndex = parentNodeXIndex;
	this->parentNodeYIndex = parentNodeYIndex;
}

/**************************************************************************************************************/

/*get the parent node x index*/
int Node::getParentXIndex()
{
	/*return the x parent node index*/
	return parentNodeXIndex;
}

/**************************************************************************************************************/

/*get the parent node y index*/
int Node::getParentYIndex()
{
	/*return the y parent node index*/
	return parentNodeYIndex;
}

/**************************************************************************************************************/

/*set the startNode*/
void Node::setStartNode(bool startNode)
{
	/*set the node*/
	this->startNode = startNode;
}

/**************************************************************************************************************/

/*get if the node is a startNode*/
bool Node::getStartNode()
{
	/*return startNode*/
	return startNode;
}

/**************************************************************************************************************/

/*set the endNode*/
void Node::setEndNode(bool endNode)
{
	/*set the node*/
	this->endNode = endNode;
}

/**************************************************************************************************************/

/*get if the node is an endNode*/
bool Node::getEndNode()
{
	/*return endNode*/
	return endNode;
}

/**************************************************************************************************************/

/*set the safe*/
void Node::setSafeNode(bool safe)
{
	/*set the node*/
	this->safe = safe;
}

/**************************************************************************************************************/

/*get if the node is an safe*/
bool Node::getSafeNode()
{
	/*return safeNode*/
	return safe;
}

/**************************************************************************************************************/

/*set the cost*/
void Node::setCostNode(int cost)
{
	/*set the node cost*/
	this->cost = cost;
}

/**************************************************************************************************************/

/*get the cost*/
int Node::getCostNode()
{
	/*return the node cost*/
	return cost;
}

/**************************************************************************************************************/

/*set the fScore*/
void Node::setFScoreNode(int fScore)
{
	/*set the node fScore*/
	this->fScore = fScore;
}

/**************************************************************************************************************/

/*get the fScore*/
int Node::getFScoreNode()
{
	/*return the node fScore*/
	return fScore;
}

/**************************************************************************************************************/

/*get the x index*/
int Node::getXIndex()
{
	/*return the node x index*/
	return nodeXIndex;
}

/**************************************************************************************************************/

/*get the y index*/
int Node::getYIndex()
{
	/*return the node y index*/
	return nodeYIndex;
}

/**************************************************************************************************************/

/*set the listed*/
void Node::setListed(bool listed)
{
	/*set the node*/
	this->listed = listed;
}

/**************************************************************************************************************/

/*get if the node is listed*/
bool Node::getListed()
{
	/*return listed*/
	return listed;
}


text:
var map;

function init() {

    var options = {
        projection: new OpenLayers.Projection("EPSG:102113"),
        units: "m",
        numZoomLevels: 18,
        maxResolution: 156543.0339,
        maxExtent: new OpenLayers.Bounds(-20037508, -20037508,
                                         20037508, 20037508.34)
    };
    map = new OpenLayers.Map('map', options);

    // create Google layer with EPSG:102113 code
    var gsat = new OpenLayers.Layer.Google("Google Imagery", {
        type: G_SATELLITE_MAP,
        sphericalMercator: true,
        projection: "EPSG:102113"
    });

    // create WMS layer
    var wms = new OpenLayers.Layer.WMS(
        "Highways",
        "http://sampleserver1.arcgisonline.com/arcgis/services/Specialty/ESRI_StateCityHighway_USA/MapServer/WMSServer",
        {layers: "2", format: "image/gif", transparent: "true"},
        {
            isBaseLayer: false,
            wrapDateLine: true
        }
    );

    map.addLayers([gsat, wms]);
    map.addControl(new OpenLayers.Control.LayerSwitcher());
    map.setCenter(new OpenLayers.LonLat(-10723197, 4500612), 3);
}


text:
"""Views for the monitoring app."""
from django.contrib.auth.decorators import login_required
from django.db.models import Count
from django.http import Http404
from django.utils.decorators import method_decorator
from django.views.generic import ListView, TemplateView

from .register import monitor

class MonitoringViewMixin(object):
    """Helper methods that all monitoring base views need."""
    view_name = None
    monitor_title = None

    @method_decorator(login_required)
    def dispatch(self, request, *args, **kwargs):  # pragma: no cover
        if not request.user.is_staff:
            raise Http404
        self.request = request
        self.monitor_name = request.GET.get('monitor')
        return super(MonitoringViewMixin, self).dispatch(
            request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        ctx = super(MonitoringViewMixin, self).get_context_data(**kwargs)
        ctx.update({
            'monitor_title': self.monitor_title,
            'monitor_name': self.monitor_name,
        })
        return ctx

    def get_template_names(self):
        """
        Returns the template name for the view based on the view's model.

        """
        return [self.model.get_template_name(), ]

    def get_view_name(self):
        """
        Returns the view name based on the view's model.

        If you have set the ``view_name`` attribute on the view, that will be
        returned instead.

        """
        if self.view_name is not None:
            return self.view_name
        return 'monitoring_{0}'.format(self.model.__name__.lower())

class IntegerCountView(MonitoringViewMixin, ListView):
    """Default view for the ``IntegerCountBase`` monitor model."""
    monitor_title = 'Integer Count'

    def get_queryset(self):
        qs = super(IntegerCountView, self).get_queryset()
        qs = qs.values('date_created').annotate(
            count=Count('date_created')).distinct()
        return qs

class MonitoringView(TemplateView):
    template_name = 'monitoring/index.html'

    @method_decorator(login_required)
    def dispatch(self, request, *args, **kwargs):
        if not request.user.is_staff:
            raise Http404
        self.request = request
        return super(MonitoringView, self).dispatch(
            request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        ctx = super(MonitoringView, self).get_context_data(**kwargs)
        ctx.update({
            'monitor': monitor,
        })
        return ctx


text:
namespace FreeRiders.Models
{
    using System.ComponentModel.DataAnnotations;

    using FreeRiders.Data.Common.Models;

    public class AlbumCategory : DeletableEntity
    {
        [Key]
        public int ID { get; set; }

        [Required]
        [StringLength(100, MinimumLength = 3)]
        public string Name { get; set; }
    }
}


text:
// Copyright 2010 Chris Patterson
//
// 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.
namespace Stact.Configuration.Internal
{
	using System;
	using Builders;
	using Magnum.Extensions;

	public class InstanceChannelProviderConfiguratorImpl<TInstance, TChannel> :
		InstanceChannelProviderConfigurator<TInstance, TChannel>
		where TInstance : class
	{
		readonly Func<InstanceProvider<TInstance, TChannel>> _instanceProvider;
		ChannelAccessor<TInstance, TChannel> _accessor;

		public InstanceChannelProviderConfiguratorImpl(Func<InstanceProvider<TInstance, TChannel>> instanceProvider)
		{
			_instanceProvider = instanceProvider;
		}

		public InstanceChannelProviderConfigurator<TInstance, TChannel> OnChannel(
			ChannelAccessor<TInstance, TChannel> accessor)
		{
			_accessor = accessor;

			return this;
		}

		public ChannelProvider<TChannel> GetChannelProvider(ChannelBuilder<TChannel> connection)
		{
			if (_accessor == null)
			{
				throw new ChannelConfigurationException(typeof(TChannel),
				                                        "No channel accessor was specified for instance: "
				                                        + typeof(TInstance).ToShortTypeName());
			}

			return new InstanceChannelProvider<TInstance, TChannel>(_instanceProvider(), _accessor);
		}
	}
}


text:
/// <reference path="../../_references.ts"/>

module powerbi.visuals.controls {
    export const AutoSizeColumnWidthDefault: boolean = true;

    export interface TablixColumnWidthObject {
        queryName: string;
        width: number;
    }

    export class TablixColumnWidthManager {
        public static columnWidthProp: DataViewObjectPropertyIdentifier = { objectName: 'general', propertyName: 'columnWidth' };
        public static autoSizeWidthProp: DataViewObjectPropertyIdentifier = { objectName: 'general', propertyName: 'autoSizeColumnWidth' };

        private columnWidths: number[];
        private tablixColumnWidthsObject: controls.TablixColumnWidthObject[];
        private previousAutoColumnSizePropertyValue: boolean;
        private tablixQueryNames: string[];
        private dataView: DataView;
        private visualObjectInstancesToPersist: VisualObjectInstance[];
        private matrixLeafNodes: MatrixVisualNode[];
        // TODO: Can we remove isMatrix and suppresNotification flag?
        private isMatrix: boolean;
        private suppressNotification: boolean;
        private currentPersistedWidths: number[];
        private callHostPersistProperties: boolean;
        private dataViewUpdated: boolean;

        constructor(dataView: DataView, isMatrix: boolean, matrixLeafNodes?: MatrixVisualNode[]) {
            this.columnWidths = [];
            this.tablixColumnWidthsObject = [];
            this.tablixQueryNames = [];
            this.dataView = dataView;
            this.matrixLeafNodes = matrixLeafNodes;
            this.isMatrix = isMatrix;
            this.suppressNotification = false;
            this.currentPersistedWidths = [];
            this.visualObjectInstancesToPersist = [];
            this.callHostPersistProperties = false;
            this.dataViewUpdated = false;
        }

        public getColumnWidths(): number[] {
            return this.columnWidths;
        }

        public getTablixColumnWidthsObject(): controls.TablixColumnWidthObject[] {
            return this.tablixColumnWidthsObject;
        }

        public updateDataView(dataView: DataView, matrixLeafNodes?: MatrixVisualNode[]): void {
            this.dataView = dataView;
            this.matrixLeafNodes = matrixLeafNodes;
            this.dataViewUpdated = true;
        }

        public getVisualObjectInstancesToPersist(): VisualObjectInstance[] {
            return this.visualObjectInstancesToPersist;
        }

        public persistColumnWidthsOnHost(): boolean {
            return this.callHostPersistProperties;
        }

        public getTablixQueryNames(): string[]{
            return this.tablixQueryNames;
        }

        public get suppressOnDataChangedNotification(): boolean {
            return this.suppressNotification;
        }

        public set suppressOnDataChangedNotification(notify: boolean) {
            this.suppressNotification = notify;
        }

        public deserializeTablixColumnWidths(): void {
            let columnMetaData = this.dataView && this.dataView.metadata && this.dataView.metadata.columns;
            if (columnMetaData) {
                let autoSize = this.shouldAutoSizeColumnWidth();
                if (this.previousAutoColumnSizePropertyValue !== undefined && !this.previousAutoColumnSizePropertyValue && this.previousAutoColumnSizePropertyValue !== autoSize) {
                    // Auto-Size false to true. In this case blow away any saved widths and revert back to default of calculating column sizes
                    this.columnWidths = [];
                    this.removePersistedVisualObjectInstances();
                    this.tablixColumnWidthsObject = [];
                    this.callHostPersistProperties = true;
                }
                else {
                    this.deserializeColumnWidths(columnMetaData);
                    this.callHostPersistProperties = false;
                }

                this.previousAutoColumnSizePropertyValue = autoSize;
            }
        }

        public columnWidthChanged(index: number, width: number): void {
            this.populateTablixQueryNames();
            if (this.tablixQueryNames.length === 0)
                return;
            // Only persist manually resized columns
            let colIndex = this.isMatrix ? index : Math.max(index - 1, 0); // Table indices are offset with an empty header.
            let newColumnWidthObj = {
                queryName: this.tablixQueryNames[colIndex],
                width: width
            };

            let objExists = false;
            for (let i = 0, len = this.tablixColumnWidthsObject.length; i < len; i++) {
                if (this.tablixColumnWidthsObject[i].queryName === newColumnWidthObj.queryName) {
                    this.tablixColumnWidthsObject[i] = newColumnWidthObj;
                    objExists = true;
                }
            }
            if (!objExists)
                this.tablixColumnWidthsObject.push(newColumnWidthObj);

            // Let onDataChanged call pass through so all instances of resized column gets updated for the matrix
            this.suppressNotification = !this.isMatrix;
            this.generateVisualObjectInstancesToPersist();
            this.callHostPersistProperties = true;
        }

        public persistAllColumnWidths(widthsToPersist: number[]): void {
            if (!this.shouldAutoSizeColumnWidth() && this.dataViewUpdated) {
                if (!_.isEqual(widthsToPersist, this.currentPersistedWidths)) {
                    this.currentPersistedWidths = widthsToPersist;
                    this.suppressNotification = true;
                }
                else {
                    this.suppressNotification = false;
                    this.callHostPersistProperties = false;
                    return;
                }
                // Persist all column widths
                let widths = this.isMatrix ? widthsToPersist
                    : widthsToPersist.slice(1, widthsToPersist.length); // Table indices are offset with an empty header.
                let savedColumnWidths: controls.TablixColumnWidthObject[] = [];
                for (let colIndex = 0, len = widths.length; colIndex < len; colIndex++) {
                    let widthObj = {
                        queryName: this.tablixQueryNames[colIndex],
                        width: widths[colIndex]
                    };

                    for (let columnWidthObject of this.tablixColumnWidthsObject) {
                        if (columnWidthObject.queryName === widthObj.queryName)
                            widthObj.width = columnWidthObject.width;
                    }
                    savedColumnWidths.push(widthObj);
                }
                this.tablixColumnWidthsObject = savedColumnWidths;
                this.generateVisualObjectInstancesToPersist();
                this.callHostPersistProperties = true;
            }
        }

        public shouldAutoSizeColumnWidth(): boolean {
            let objects = this.dataView.metadata.objects;
            if (objects && objects[TablixColumnWidthManager.autoSizeWidthProp.objectName]) {
                return objects[TablixColumnWidthManager.autoSizeWidthProp.objectName][TablixColumnWidthManager.autoSizeWidthProp.propertyName] !== false;
            }

            // Auto adjust is turned on by default
            return AutoSizeColumnWidthDefault;
        }

        private generateVisualObjectInstancesToPersist(): void {
            this.visualObjectInstancesToPersist = [];
            // Auto-Size property
            this.visualObjectInstancesToPersist.push({
                selector: null,
                objectName: 'general',
                properties: {
                    autoSizeColumnWidth: data.SQExprBuilder.boolean(this.shouldAutoSizeColumnWidth())
                }
            });

            // Column Widths
            for (let columnWidthObject of this.tablixColumnWidthsObject) {
                this.visualObjectInstancesToPersist.push({
                    selector: { metadata: columnWidthObject.queryName },
                    objectName: 'general',
                    properties: {
                        columnWidth: data.SQExprBuilder.double(columnWidthObject.width)
                    }
                });
            }
        }

        private removePersistedVisualObjectInstances(): void {
            this.visualObjectInstancesToPersist = [];
            // Auto-Size property
            this.visualObjectInstancesToPersist.push({
                selector: null,
                objectName: 'general',
                properties: {
                    autoSizeColumnWidth: data.SQExprBuilder.boolean(this.shouldAutoSizeColumnWidth())
                }
            });

            for (let columnWidthObject of this.tablixColumnWidthsObject) {
                this.visualObjectInstancesToPersist.push({
                    selector: { metadata: columnWidthObject.queryName },
                    objectName: 'general',
                    properties: {
                        columnWidth: undefined
                    }
                });
            }
        }

        private deserializeColumnWidths(columnMetaData: DataViewMetadataColumn[]): void {
            this.columnWidths.length = 0;
            this.tablixColumnWidthsObject.length = 0;
            this.populateTablixQueryNames();
            if (this.tablixQueryNames.length === 0)
                return;
            for (let column of columnMetaData) {
                if (!column.objects || !column.objects[TablixColumnWidthManager.columnWidthProp.objectName][TablixColumnWidthManager.columnWidthProp.propertyName])
                    continue;
                for (let colIndex = 0, len = this.tablixQueryNames.length; colIndex < len; colIndex++) {
                    let propertySelector = this.tablixQueryNames[colIndex];
                    if (column.queryName === propertySelector) {
                        let columnWidth = <number>column.objects[TablixColumnWidthManager.columnWidthProp.objectName][TablixColumnWidthManager.columnWidthProp.propertyName];
                        let index = this.isMatrix ? colIndex : colIndex + 1; // Table indices are offset with an empty header.
                        this.columnWidths[index] = columnWidth;
                        this.tablixColumnWidthsObject.push({
                            queryName: propertySelector,
                            width: columnWidth
                        });
                    }
                }
            }
        }

        private populateTablixQueryNames(): void {
            if (this.isMatrix)
                this.getMatrixQueryNames();
            else
                this.getTableQueryNames();
        }

        private getTableQueryNames(): void {
            this.tablixQueryNames.length = 0;
            let columnMetaData = this.dataView.table.columns;
            for (let column of columnMetaData) {
                this.tablixQueryNames.push(column.queryName);
            }
        }

        private getMatrixQueryNames(): void {
            this.tablixQueryNames.length = 0;
            let matrixRows = this.dataView.matrix.rows;
            for (let level of matrixRows.levels) {
                for (let source of level.sources) {
                    this.tablixQueryNames.push(source.queryName);
                }
            }

            if (this.matrixLeafNodes) {
                for (let leafNode of this.matrixLeafNodes) {
                    this.tablixQueryNames.push(leafNode.queryName);
                }
            }
        }
    }
}


text:
package robustsession

import (
	"net/http"
	"time"
)

func setupTLSHandshakeTimeout(transport *http.Transport, timeout time.Duration) {
	transport.TLSHandshakeTimeout = timeout
}


text:
const assert = require('assert');
const chai   = require('chai');
const chaiAlmost = require('chai-almost');
const expect = chai.expect

const ElapsedTime = require('../dist/tcx.js').ElapsedTime;

//chai.use(chaiAlmost());
chai.use(chaiAlmost(0.00000001));

// https://www.chaijs.com/api/assert/#method_istrue

describe('ElapsedTime', function() {

  describe('#constructor()', function() {

    it('It should define constant values', function() {
      expect(ElapsedTime.MILLISECONDS_PER_SECOND).to.be.almost(1000.0);
      expect(ElapsedTime.SECONDS_PER_HOUR).to.be.almost(3600.0);
      expect(ElapsedTime.SECONDS_PER_MINUTE).to.be.almost(60.0);

      ElapsedTime.MILLISECONDS_PER_SECOND = 0;

      expect(ElapsedTime.MILLISECONDS_PER_SECOND).to.be.almost(1000.0);
      expect(ElapsedTime.SECONDS_PER_HOUR).to.be.almost(3600.0);
      expect(ElapsedTime.SECONDS_PER_MINUTE).to.be.almost(60.0);
    });

    it('It should return the correct value for 0 ms', function() {
      var ms = 0;
      var et = new ElapsedTime(ms);
      chai.assert.isTrue(et.elapsedMs === ms, 'the ElapsedTime elapsedMs value is incorrect');
      chai.assert.isTrue(et.secs === 0, 'the ElapsedTime secs value is incorrect');
      chai.assert.isTrue(et.hh === 0, 'the ElapsedTime hh value is incorrect');
      chai.assert.isTrue(et.mm === 0, 'the ElapsedTime mm value is incorrect');
      chai.assert.isTrue(et.ss === 0, 'the ElapsedTime ss value is incorrect');
      chai.assert.isTrue(et.asHHMMSS() === '00:00:00', 'the ElapsedTime asHHMMSS() value is incorrect');
    });

    it('It should return the correct value for 1000 ms', function() {
      var ms = 1000;
      var et = new ElapsedTime(ms);
      chai.assert.isTrue(et.elapsedMs === ms, 'the ElapsedTime elapsedMs value is incorrect');
      chai.assert.isTrue(et.secs === 1, 'the ElapsedTime secs value is incorrect');
      chai.assert.isTrue(et.hh === 0, 'the ElapsedTime hh value is incorrect');
      chai.assert.isTrue(et.mm === 0, 'the ElapsedTime mm value is incorrect');
      chai.assert.isTrue(et.ss === 1, 'the ElapsedTime ss value is incorrect');
      chai.assert.isTrue(et.asHHMMSS() === '00:00:01', 'the ElapsedTime asHHMMSS() value is incorrect');
    });

    it('It should return the correct value for -1000 ms', function() {
      var ms = -1000;
      var et = new ElapsedTime(ms);
      chai.assert.isTrue(et.elapsedMs === 1000, 'the ElapsedTime elapsedMs value is incorrect');
      chai.assert.isTrue(et.secs === 1, 'the ElapsedTime secs value is incorrect');
      chai.assert.isTrue(et.hh === 0, 'the ElapsedTime hh value is incorrect');
      chai.assert.isTrue(et.mm === 0, 'the ElapsedTime mm value is incorrect');
      chai.assert.isTrue(et.ss === 1, 'the ElapsedTime ss value is incorrect');
      chai.assert.isTrue(et.asHHMMSS() === '00:00:01', 'the ElapsedTime asHHMMSS() value is incorrect');
    });

    it('It should return the correct value for 62000 ms', function() {
      var ms = 62000;
      var et = new ElapsedTime(ms);
      chai.assert.isTrue(et.elapsedMs === ms, 'the ElapsedTime elapsedMs value is incorrect');
      chai.assert.isTrue(et.secs === 62, 'the ElapsedTime secs value is incorrect');
      chai.assert.isTrue(et.hh === 0, 'the ElapsedTime hh value is incorrect');
      chai.assert.isTrue(et.mm === 1, 'the ElapsedTime mm value is incorrect');
      chai.assert.isTrue(et.ss === 2, 'the ElapsedTime ss value is incorrect');
      chai.assert.isTrue(et.asHHMMSS() === '00:01:02', 'the ElapsedTime asHHMMSS() value is incorrect');
    });

    it('It should return the correct value for 3663000 ms', function() {
      var ms = 3663000;
      var et = new ElapsedTime(ms);
      chai.assert.isTrue(et.elapsedMs === ms, 'the ElapsedTime elapsedMs value is incorrect');
      chai.assert.isTrue(et.secs === 3663, 'the ElapsedTime secs value is incorrect');
      chai.assert.isTrue(et.hh === 1, 'the ElapsedTime hh value is incorrect');
      chai.assert.isTrue(et.mm === 1, 'the ElapsedTime mm value is incorrect');
      chai.assert.isTrue(et.ss === 3, 'the ElapsedTime ss value is incorrect');
      chai.assert.isTrue(et.asHHMMSS() === '01:01:03', 'the ElapsedTime asHHMMSS() value is incorrect');
    });

    it('It should return the correct value for 3663200 ms', function() {
      var ms = 3663200;  // round down
      var et = new ElapsedTime(ms);
      chai.assert.isTrue(et.elapsedMs === ms, 'the ElapsedTime elapsedMs value is incorrect');
      chai.assert.isTrue(et.secs === 3663, 'the ElapsedTime secs value is incorrect');
      chai.assert.isTrue(et.hh === 1, 'the ElapsedTime hh value is incorrect');
      chai.assert.isTrue(et.mm === 1, 'the ElapsedTime mm value is incorrect');
      chai.assert.isTrue(et.ss === 3, 'the ElapsedTime ss value is incorrect');
      chai.assert.isTrue(et.asHHMMSS() === '01:01:03', 'the ElapsedTime asHHMMSS() value is incorrect');
    });

    it('It should return the correct value for 3663700.1 ms', function() {
      var ms = 3663700.1;  // round up, with fraction
      var et = new ElapsedTime(ms);
      chai.assert.isTrue(et.elapsedMs === ms, 'the ElapsedTime elapsedMs value is incorrect');
      chai.assert.isTrue(et.secs === 3664, 'the ElapsedTime secs value is incorrect');
      chai.assert.isTrue(et.hh === 1, 'the ElapsedTime hh value is incorrect');
      chai.assert.isTrue(et.mm === 1, 'the ElapsedTime mm value is incorrect');
      chai.assert.isTrue(et.ss === 4, 'the ElapsedTime ss value is incorrect');
      chai.assert.isTrue(et.asHHMMSS() === '01:01:04', 'the ElapsedTime asHHMMSS() value is incorrect');
    });

  });

});


text:
package org.jutge.joc.porra.entitystash.aspect;

import java.util.List;
import java.util.Locale;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.jutge.joc.porra.entitystash.annotation.EntityStashManaged;
import org.jutge.joc.porra.entitystash.module.EntityStashEntityModule;
import org.jutge.joc.porra.entitystash.module.EntityStashViewModule;
import org.jutge.joc.porra.entitystash.service.EntityStashEntityService;
import org.jutge.joc.porra.entitystash.service.EntityStashViewService;
import org.jutge.joc.porra.entitystash.stash.EntityStash;
import org.jutge.joc.porra.entitystash.utils.EntityStashUtils;
import org.jutge.joc.porra.model.account.Account;
import org.jutge.joc.porra.model.league.League;
import org.jutge.joc.porra.model.player.Player;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

/**
 * Entity stash aspect.
 * Can query DB and stash data to minimize app-DB interaction.
 * Can inject additional request params. These are json strings.
 * @author Llop
 */
@Aspect
public class EntityStashAspect {

	public static final String DEFAULT_LEAGUE_NAME = "FIB";
	public static final String DEFAULT_LEAGUE_INFO = "defaultLeagueInfo";
	public static final String DEFAULT_LEAGUE_STATS = "defaultLeagueStats";
	public static final String DEFAULT_LEAGUE_POPULAR_PLAYERS = "defaultLeaguePopularPlayers";
	public static final String DEFAULT_LEAGUE_ALIVE_PLAYERS = "defaultLeaguePlayers";
	public static final String DEFAULT_LEAGUE_BET_RESTRICTIONS = "defaultLeagueBetRestrictions";
	public static final String ACCOUNT_BET_RESTRICTIONS = "accountBetRestrictions";
	public static final String ACCOUNT_INFO = "accountInfo";
	public static final String ACCOUNT_BETS = "accountBets";
	public static final String RICHEST_ACCOUNTS = "richestAccounts";

	private final Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired private EntityStashEntityService entityStashEntityService;
	@Autowired private EntityStashViewService entityStashViewService;

	@Before(value="within(org.jutge.joc.porra.controller..*) && @annotation(entityStashManaged)")
	public void stashEntities(final JoinPoint joinPoint, final EntityStashManaged entityStashManaged) {
		this.logger.info("EntityStashAspect.stashEntities");
		final EntityStash entityStash = this.getEntityStash(joinPoint);
		this.applyEntityModules(entityStash, entityStashManaged);
		final RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
		requestAttributes.setAttribute(EntityStashUtils.ENTITY_STASH, entityStash, RequestAttributes.SCOPE_REQUEST);
	}

	private EntityStash getEntityStash(final JoinPoint joinPoint) {
		final Object[] args = joinPoint.getArgs();
		for (final Object obj : args) {
			if (obj instanceof EntityStash) {
				return (EntityStash)obj;
			}
		}
		return new EntityStash();
	}

	private void applyEntityModules(final EntityStash entityStash, final EntityStashManaged entityStashManaged) {
		List<League> leagues = null;
		List<Player> players = null;
		Account account = null;
		final EntityStashEntityModule[] entities = entityStashManaged.entities();
		for (EntityStashEntityModule entity : entities) {
			if (entity == EntityStashEntityModule.LEAGUES || entity == EntityStashEntityModule.ALL) {
				leagues = this.entityStashEntityService.getLeagues();
			}
			if (entity == EntityStashEntityModule.PLAYERS || entity == EntityStashEntityModule.ALL) {
				players = this.entityStashEntityService.getPlayers();
			}
			if (entity == EntityStashEntityModule.ACCOUNT || entity == EntityStashEntityModule.ALL) {
				account = this.entityStashEntityService.getAccount();
			}
		}
		entityStash.init(leagues, players, account);
	}

	@After("within(org.jutge.joc.porra.controller..*) && @annotation(entityStashManaged)")
	public void stashViews(final EntityStashManaged entityStashManaged) {
		this.logger.info("EntityStashAspect.stashViews");
		final Locale locale = LocaleContextHolder.getLocale();
		final RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
		final EntityStash entityStash = (EntityStash)requestAttributes.getAttribute(EntityStashUtils.ENTITY_STASH, RequestAttributes.SCOPE_REQUEST);
		final EntityStashViewModule[] views = entityStashManaged.views();
		for (EntityStashViewModule view : views) {
			try {
				if (view == EntityStashViewModule.LEAGUE_INFO || view == EntityStashViewModule.ALL) {
					final League defaultLeague = entityStash.getLeague(DEFAULT_LEAGUE_NAME);
					final String leagueInfo = this.entityStashViewService.getLeagueInfo(defaultLeague, locale);
					requestAttributes.setAttribute(DEFAULT_LEAGUE_INFO, leagueInfo, RequestAttributes.SCOPE_REQUEST);
				}
				if (view == EntityStashViewModule.LEAGUE_STATS || view == EntityStashViewModule.ALL) {
					final League defaultLeague = entityStash.getLeague(DEFAULT_LEAGUE_NAME);
					final String leagueStats = this.entityStashViewService.getLeagueStats(defaultLeague, locale);
					requestAttributes.setAttribute(DEFAULT_LEAGUE_STATS, leagueStats, RequestAttributes.SCOPE_REQUEST);
				}
				if (view == EntityStashViewModule.LEAGUE_POPULAR_PLAYERS || view == EntityStashViewModule.ALL) {
					final League defaultLeague = entityStash.getLeague(DEFAULT_LEAGUE_NAME);
					final String leaguePopularPlayers = this.entityStashViewService.getLeaguePopularPlayers(defaultLeague, locale);
					requestAttributes.setAttribute(DEFAULT_LEAGUE_POPULAR_PLAYERS, leaguePopularPlayers, RequestAttributes.SCOPE_REQUEST);
				}
				if (view == EntityStashViewModule.LEAGUE_ALIVE_PLAYERS || view == EntityStashViewModule.ALL) {
					final League defaultLeague = entityStash.getLeague(DEFAULT_LEAGUE_NAME);
					final List<Player> leaguePlayers = entityStash.getLeaguePlayers(defaultLeague);
					final String alivePlayers = this.entityStashViewService.getAlivePlayers(leaguePlayers);
					requestAttributes.setAttribute(DEFAULT_LEAGUE_ALIVE_PLAYERS, alivePlayers, RequestAttributes.SCOPE_REQUEST);
				}
				if (view == EntityStashViewModule.LEAGUE_BET_RESTRICTIONS || view == EntityStashViewModule.ALL) {
					final League defaultLeague = entityStash.getLeague(DEFAULT_LEAGUE_NAME);
					final String leagueBetRestrictions = this.entityStashViewService.getLeagueBetRestrictions(defaultLeague, locale);
					requestAttributes.setAttribute(DEFAULT_LEAGUE_BET_RESTRICTIONS, leagueBetRestrictions, RequestAttributes.SCOPE_REQUEST);
				}
				if (view == EntityStashViewModule.ACCOUNT_BET_RESTRICTIONS || view == EntityStashViewModule.ALL) {
					final Account account = entityStash.getAccount();
					final String accountBetRestrictions = this.entityStashViewService.getAccountBetRestrictions(account, locale);
					requestAttributes.setAttribute(ACCOUNT_BET_RESTRICTIONS, accountBetRestrictions, RequestAttributes.SCOPE_REQUEST);
				}
				if (view == EntityStashViewModule.RICHEST_ACCOUNTS || view == EntityStashViewModule.ALL) {
					final String richestAccounts = this.entityStashViewService.getRichestAccounts(entityStash, locale);
					requestAttributes.setAttribute(RICHEST_ACCOUNTS, richestAccounts, RequestAttributes.SCOPE_REQUEST);
				}
				if (view == EntityStashViewModule.ACCOUNT_INFO || view == EntityStashViewModule.ALL) {
					final Account account = entityStash.getAccount();
					if (account != null) {
						final String accountInfo = this.entityStashViewService.getAccountInfo(account, locale);
						requestAttributes.setAttribute(ACCOUNT_INFO, accountInfo, RequestAttributes.SCOPE_REQUEST);
					}
				}
				if (view == EntityStashViewModule.ACCOUNT_BETS || view == EntityStashViewModule.ALL) {
					final Account account = entityStash.getAccount();
					if (account != null) {
						final String accountBets = this.entityStashViewService.getAccountBets(account, entityStash, locale);
						requestAttributes.setAttribute(ACCOUNT_BETS, accountBets, RequestAttributes.SCOPE_REQUEST);
					}
				}
			} catch (Exception exception) {
				this.logger.error(exception.getMessage());
			}
		}
	}

}


text:
- mbr update, remove versions.json

- Bump to version 0.1.1

## [v0.1.0] (https://github.com/CollectionFS/Meteor-cfs-tempstore/tree/v0.1.0)
#### 17/12/14 by Morten Henriksen
- mbr update versions and fix warnings

- fix 0.9.1 package scope

- don't rely on package names; fix for 0.9.1

- 0.9.1 support

## [v0.0.29] (https://github.com/CollectionFS/Meteor-cfs-tempstore/tree/v0.0.29)
#### 28/08/14 by Morten Henriksen
- Meteor Package System Update

## [v0.0.28] (https://github.com/CollectionFS/Meteor-cfs-tempstore/tree/v0.0.28)
#### 27/08/14 by Eric Dobbertin
- change package name to lowercase

## [v0.0.27] (https://github.com/CollectionFS/Meteor-cfs-tempstore/tree/v0.0.27)
#### 17/06/14 by Eric Dobbertin
- add `FS.TempStore.removeAll` method

## [v0.0.26] (https://github.com/CollectionFS/Meteor-cfs-tempstore/tree/v0.0.26)
#### 30/04/14 by Eric Dobbertin
## [v0.0.25] (https://github.com/CollectionFS/Meteor-cfs-tempstore/tree/v0.0.25)
#### 30/04/14 by Eric Dobbertin
- use third-party combined-stream node pkg as attempt to resolve pesky streaming issues

## [v0.0.24] (https://github.com/CollectionFS/Meteor-cfs-tempstore/tree/v0.0.24)
#### 29/04/14 by Eric Dobbertin
- generate api docs

- fileKey methods now expect an FS.File always, so we give them one

- small FS.File API change

## [v0.0.23] (https://github.com/CollectionFS/Meteor-cfs-tempstore/tree/v0.0.23)
#### 12/04/14 by Eric Dobbertin
- test for packages since we're assigning default error functions for stores

## [v0.0.22] (https://github.com/CollectionFS/Meteor-cfs-tempstore/tree/v0.0.22)
#### 12/04/14 by Eric Dobbertin
- avoid errors if file already removed from temp store

## [v0.0.21] (https://github.com/CollectionFS/Meteor-cfs-tempstore/tree/v0.0.21)
#### 12/04/14 by Eric Dobbertin
## [v0.0.20] (https://github.com/CollectionFS/Meteor-cfs-tempstore/tree/v0.0.20)
#### 08/04/14 by Eric Dobbertin
- cleanup stored/uploaded events and further improve chunk tracking

## [v0.0.19] (https://github.com/CollectionFS/Meteor-cfs-tempstore/tree/v0.0.19)
#### 08/04/14 by Eric Dobbertin
- use internal tracking collection

- Have TempStore set the size

- Add the SA on stored result

- allow unset chunkSum

## [v0.0.18] (https://github.com/CollectionFS/Meteor-cfs-tempstore/tree/v0.0.18)
#### 06/04/14 by Eric Dobbertin
- delete chunkCount and chunkSize props from fileObj after upload is complete

## [v0.0.17] (https://github.com/CollectionFS/Meteor-cfs-tempstore/tree/v0.0.17)
#### 06/04/14 by Eric Dobbertin
- We now wait to mount storage until it's needed (first upload begins); this ensures that we are able to accurately check for the cfs-worker package, which loads after this one. It also makes the code a bit cleaner.

## [v0.0.16] (https://github.com/CollectionFS/Meteor-cfs-tempstore/tree/v0.0.16)
#### 04/04/14 by Morten Henriksen
- Temporary workaround: We currently we generate a mongoId if gridFS is used for TempStore

- Note: At the moment tempStore will only use gridfs if no filesystem is installed

## [v0.0.15] (https://github.com/CollectionFS/Meteor-cfs-tempstore/tree/v0.0.15)
#### 02/04/14 by Morten Henriksen
- Use the stored event and object instead (result object is not used at the moment - but we could store an id at some point)

## [v0.0.14] (https://github.com/CollectionFS/Meteor-cfs-tempstore/tree/v0.0.14)
#### 31/03/14 by Eric Dobbertin
- use latest releases

- use latest releases

## [v0.0.13] (https://github.com/CollectionFS/Meteor-cfs-tempstore/tree/v0.0.13)
#### 31/03/14 by Morten Henriksen
- Try to use latest when using weak deps

## [v0.0.12] (https://github.com/CollectionFS/Meteor-cfs-tempstore/tree/v0.0.12)
#### 30/03/14 by Morten Henriksen
## [v0.0.11] (https://github.com/CollectionFS/Meteor-cfs-tempstore/tree/v0.0.11)
#### 30/03/14 by Morten Henriksen
- Set noon callback - we just want the file gone

## [v0.0.10] (https://github.com/CollectionFS/Meteor-cfs-tempstore/tree/v0.0.10)
#### 29/03/14 by Morten Henriksen
- add filesystem and gridfs as weak deps

## [v0.0.9] (https://github.com/CollectionFS/Meteor-cfs-tempstore/tree/v0.0.9)
#### 29/03/14 by Morten Henriksen
- Add check to see if FS.TempStore.Storage is set

## [v0.0.8] (https://github.com/CollectionFS/Meteor-cfs-tempstore/tree/v0.0.8)
#### 29/03/14 by Morten Henriksen
- Converting TempStore to use SA api

## [v0.0.7] (https://github.com/CollectionFS/Meteor-cfs-tempstore/tree/v0.0.7)
#### 25/03/14 by Morten Henriksen
- use `new Date`

- Have TempStore emit relevant events

## [v0.0.6] (https://github.com/CollectionFS/Meteor-cfs-tempstore/tree/v0.0.6)
#### 23/03/14 by Morten Henriksen
- Rollback to specific git dependency

- use collectionFS travis version force update

## [v0.0.5] (https://github.com/CollectionFS/Meteor-cfs-tempstore/tree/v0.0.5)
#### 22/03/14 by Morten Henriksen
- try to fix travis test by using general package references

## [v0.0.4] (https://github.com/CollectionFS/Meteor-cfs-tempstore/tree/v0.0.4)
#### 21/03/14 by Morten Henriksen
- fix chunk files not actually being deleted

## [v0.0.3] (https://github.com/CollectionFS/Meteor-cfs-tempstore/tree/v0.0.3)
#### 18/03/14 by Morten Henriksen
- * TempStore is now an EventEmitter   * progress event   * uploaded   * (start) should perhaps be created   * remove * Added FS.TempStore.listParts - will return lookup object listing the parts already uploaded

- Allow chunk to be undefined an thereby have the createWriteStream follow normal streaming api

- Allow undefined in chunkPath

- added comments

- bug hunting

- Add streaming WIP

- rename temp store collection to 'cfs.tempstore'

- fix ensureForFile

- track tempstore chunks in our own collection rather than in the file object

- change to accept buffer; less converting

- prevent bytesUploaded from getting bigger than size

## [v0.0.2] (https://github.com/CollectionFS/Meteor-cfs-tempstore/tree/v0.0.2)
#### 15/02/14 by Morten Henriksen
- fix typo

## [v0.0.1] (https://github.com/CollectionFS/Meteor-cfs-tempstore/tree/v0.0.1)
#### 13/02/14 by Morten Henriksen
- init commit


text:
"""
This is part of WebScout software
Docs EN: http://hack4sec.pro/wiki/index.php/WebScout_en
Docs RU: http://hack4sec.pro/wiki/index.php/WebScout
License: MIT
Copyright (c) Anton Kuzmin <http://anton-kuzmin.ru> (ru) <http://anton-kuzmin.pro> (en)

Job class for Spider module
"""

import Queue
import time

from classes.Registry import Registry
from classes.kernel.WSJob import WSJob
from libs.common import mongo_result_to_list

class SpiderJob(WSJob):
    """ Job class for Spider module """
    get_blocked = False

    def __init__(self, maxsize=0):
        WSJob.__init__(self, maxsize)
        self._db = Registry().get('mongo')

    def _fill_queue(self):
        """ Inner method for fill mongo collection """
        links = self._db.spider_urls.find({'checked': 0, 'getted': 0}).limit(10)
        links = mongo_result_to_list(links)

        if len(links):
            for link in links:
                link['getted'] = 1
                self._db.spider_urls.update({'hash': link['hash']}, {'$set': {'getted': 1}})

            for link in links:
                self.put(link)

    def get(self, block=True, timeout=None):
        """ Get next element from queue """
        if self.empty():
            while self.get_blocked:
                time.sleep(1)
            self.get_blocked = True
            self._fill_queue()
            self.get_blocked = False

        if self.empty():
            raise Queue.Empty

        return WSJob.get(self, block, timeout)

    def get_many(self):
        """ Get many next elements from queue """
        result = []
        try:
            while len(result) < int(Registry().get('config')['spider']['links_one_time_in_work']):
                result.append(self.get())
        except Queue.Empty:
            if not len(result):
                raise Queue.Empty

        return result

    def have_work_links(self):
        """ Are we have any work elements in collection? """
        return bool(self._db.spider_urls.find({'checked': 0}).count())

    def qsize(self):
        """ Size of queue """
        return self._db.spider_urls.find({'checked': 0}).count()


text:
The Database folder holds the various database elements used to build the database.

Contains:

- `tables`, for the various tables & their structures.
- `alterations`, for the various alterations made to tables.
- `procedures`, for the various procedures made to interact with the database.

There are 4 main groups of tables:

| Table | Purpose |
| ---- | ---- |
| **Core** |
| *Metadata* | Unindexed fields relating to other tables |
| *Year* | Contains 'years', exists almost entirely for semantic reasons - linked to by other tables |
| **User** |
| *User* | |
| *Authentication* | Temporary tokens for authentication which are destroyed when the user has finished authenticating |
| *Token* | Permanent tokens used to identify a user in lieu of their username & password once authenticated |
| *User-Year Map* | Links a user to a year they are part of |
| **Groups** |
| *Group* | When a group of students is formed, the metadata for it is stored here |
| *Group-Student Map* | The 'group' is linked to its students via this map |
| **Projects** |
| *Project* | When a project is proposed, its metadata is stored here |
| *Project-Supervisor Map* | Links a project to the supervisors responsible for it |


text:
--TEST--
V8\Context
--SKIPIF--
<?php if (!extension_loaded("v8")) print "skip"; ?>
--FILE--
<?php

/** @var \Phpv8Testsuite $helper */
$helper = require '.testsuite.php';

require '.v8-helpers.php';
$v8_helper = new PhpV8Helpers($helper);

$isolate = new \V8\Isolate();

$context = new \V8\Context($isolate);

$helper->method_matches_instanceof($context, 'globalObject', \V8\ObjectValue::class);

$global = $context->globalObject();

$v8_helper->CHECK($global->sameValue($context->globalObject()), '$global->sameValue($context->globalObject())');

$helper->method_matches($context, 'isCodeGenerationFromStringsAllowed', true);
$v8_helper->CompileTryRun($context, 'eval("1+1")');

$helper->assert('Code generation allowed', $context->isCodeGenerationFromStringsAllowed() === true);

$context->allowCodeGenerationFromStrings(false);

$helper->assert('Code generation is not allowed', $context->isCodeGenerationFromStringsAllowed() === false);

$helper->method_matches_with_output($context, 'isCodeGenerationFromStringsAllowed', false);
$res = $v8_helper->CompileTryRun($context, 'eval("1+1")');

$context->setErrorMessageForCodeGenerationFromStrings(new \V8\StringValue($isolate, 'Whoa! Nope. No eval this time, sorry.'));
$res = $v8_helper->CompileTryRun($context, 'eval("2+2")');

?>
--EXPECT--
V8\Context::globalObject() result is instance of V8\ObjectValue
CHECK $global->sameValue($context->globalObject()): OK
V8\Context::isCodeGenerationFromStringsAllowed() matches expected value
Code generation allowed: ok
Code generation is not allowed: ok
V8\Context::isCodeGenerationFromStringsAllowed() matches expected false
eval("1+1"): V8\Exceptions\TryCatchException: EvalError: Code generation from strings disallowed for this context
eval("2+2"): V8\Exceptions\TryCatchException: EvalError: Whoa! Nope. No eval this time, sorry.


text:
<?xml version="1.0" encoding="UTF-8"?>
<project name="ZenilibActivity" default="help">

    <!-- The local.properties file is created and updated by the 'android' tool.
         It contains the path to the SDK. It should *NOT* be checked into
         Version Control Systems. -->
    <property file="local.properties" />

    <!-- The ant.properties file can be created by you. It is only edited by the
         'android' tool to add properties to it.
         This is the place to change some Ant specific build properties.
         Here are some properties you may want to change/update:

         source.dir
             The name of the source directory. Default is 'src'.
         out.dir
             The name of the output directory. Default is 'bin'.

         For other overridable properties, look at the beginning of the rules
         files in the SDK, at tools/ant/build.xml

         Properties related to the SDK location or the project target should
         be updated using the 'android' tool with the 'update' action.

         This file is an integral part of the build system for your
         application and should be checked into Version Control Systems.

         -->
    <property file="ant.properties" />

    <!-- The project.properties file is created and updated by the 'android'
         tool, as well as ADT.

         This contains project specific properties such as project target, and library
         dependencies. Lower level build properties are stored in ant.properties
         (or in .classpath for Eclipse projects).

         This file is an integral part of the build system for your
         application and should be checked into Version Control Systems. -->
    <loadproperties srcFile="project.properties" />

    <!-- quick check on sdk.dir -->
    <fail
            message="sdk.dir is missing. Make sure to generate local.properties using 'android update project' or to inject it through an env var"
            unless="sdk.dir"
    />

<!-- extension targets. Uncomment the ones where you want to do custom work
     in between standard targets -->
<!--
    <target name="-pre-build">
    </target>
    <target name="-pre-compile">
    </target>

    /* This is typically used for code obfuscation.
       Compiled code location: ${out.classes.absolute.dir}
       If this is not done in place, override ${out.dex.input.absolute.dir} */
    <target name="-post-compile">
    </target>
-->
    <target name="-package-resources" depends="-crunch">
      <!-- only package resources if *not* a library project -->
      <do-only-if-not-library elseText="Library project: do not package resources..." >
        <aapt executable="${aapt}"
              command="package"
              versioncode="${version.code}"
              versionname="${version.name}"
              debug="${build.is.packaging.debug}"
              manifest="AndroidManifest.xml"
              assets="${asset.absolute.dir}"
              androidjar="${project.target.android.jar}"
              apkfolder="${out.absolute.dir}"
              nocrunch="${build.packaging.nocrunch}"
              resourcefilename="${resource.package.file.name}"
              resourcefilter="${aapt.resource.filter}"
              libraryResFolderPathRefid="project.library.res.folder.path"
              libraryPackagesRefid="project.library.packages"
              previousBuildType="${build.last.target}"
              buildType="${build.target}">
          <res path="${out.res.absolute.dir}" />
          <res path="${resource.absolute.dir}" />
          <nocompress /> <!-- forces no compression on any files in assets or res/raw -->
          <!-- <nocompress extension="xml" /> forces no compression on specific file extensions in assets and res/raw -->
        </aapt>
      </do-only-if-not-library>
    </target>

    <!-- Import the actual build file.

         To customize existing targets, there are two options:
         - Customize only one target:
             - copy/paste the target into this file, *before* the
               <import> task.
             - customize it to your needs.
         - Customize the whole content of build.xml
             - copy/paste the content of the rules files (minus the top node)
               into this file, replacing the <import> task.
             - customize to your needs.

         ***********************
         ****** IMPORTANT ******
         ***********************
         In all cases you must update the value of version-tag below to read 'custom' instead of an integer,
         in order to avoid having your file be overridden by tools such as "android update project"
    -->
    <!-- version-tag: 1 -->
    <import file="${sdk.dir}/tools/ant/build.xml" />

</project>


text:
Dictionary
==========

A small ajax based Dictionary app


text:
package edu.wustl.cab2b.server.util;

import static edu.wustl.cab2b.server.path.PathConstants.FIELD_SEPARATOR;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Connection;

import edu.wustl.cab2b.server.path.PathConstants;
import junit.framework.TestCase;

/**
 * @author chandrakant_talele
 */
public class DataFileLoaderTest extends TestCase {
    private static Connection con = TestConnectionUtil.getConnection();
    private static String tableName = "T_"+System.currentTimeMillis();
    private File file = null;

    @Override
    protected void setUp() throws Exception {
        String createTableSQL = "create table "+tableName+" (ID BIGINT(38) NOT NULL, NAME VARCHAR(10) NULL,PRIMARY KEY (ID))";
        SQLQueryUtil.executeUpdate(createTableSQL, con);
    }

    public void testLoadDataFromFile() {
        assertTrue(true);
        String str = "S";
        String home = System.getProperty("user.home");
        file = new File(home, "GeneratedFromDataFileLoaderTest.txt");
        String fileName = file.getAbsolutePath();
        file.delete();
        try {
            file.createNewFile();
            BufferedWriter fileWriter = new BufferedWriter(new FileWriter(file));
            for (int i = 1; i < 101; i++) {
                fileWriter.write(Long.toString(i));
                fileWriter.write(FIELD_SEPARATOR);
                fileWriter.write(str + i);
                fileWriter.write("\n");
                fileWriter.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
            assertTrue("Unable to write to file " + fileName, false);
        }
        String columns = "(ID,NAME)";

        Class<?>[] dataTypes = {Long.class,String.class};
        new DataFileLoader().loadDataFromFile(con, fileName, columns, tableName, dataTypes,PathConstants.FIELD_SEPARATOR);

        String selectSQL = "SELECT ID,NAME FROM " +tableName;
        int recordCount = 0;
        String[][] rs = null;

        rs = SQLQueryUtil.executeQuery(selectSQL, con);

        for (int i = 0; i < rs.length; i++) {
            recordCount++;
            Long id = Long.parseLong(rs[i][0]);
            String name = (String) rs[i][1];
            assertTrue(id > 0 && id < 101);
            assertTrue(name.startsWith(str));
        }
        assertEquals(100, recordCount);
        file.delete();
    }

    /**
     * @see junit.framework.TestCase#tearDown()
     */
    @Override
    protected void tearDown() throws Exception {
        if (file != null) {
            file.delete();
        }
        SQLQueryUtil.executeUpdate("DROP table " +tableName, con);
    }

    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        TestConnectionUtil.close(con);
    }
}