text:
package org.apache.hadoop.net;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hdfs.DFSTestUtil;
import org.apache.hadoop.hdfs.HdfsConfiguration;
import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.apache.hadoop.hdfs.protocol.DatanodeInfo;
import org.apache.hadoop.hdfs.protocol.HdfsConstants.DatanodeReportType;
import org.apache.hadoop.hdfs.server.blockmanagement.DatanodeDescriptor;
import org.apache.hadoop.hdfs.server.protocol.NamenodeProtocols;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.Timeout;

public class TestNetworkTopology {
  private static final Log LOG = LogFactory.getLog(TestNetworkTopology.class);
  private final static NetworkTopology cluster =
      NetworkTopology.getInstance(new Configuration());
  private DatanodeDescriptor dataNodes[];

  @Rule
  public Timeout testTimeout = new Timeout(30000);

  @Before
  public void setupDatanodes() {
    dataNodes = new DatanodeDescriptor[] {
        DFSTestUtil.getDatanodeDescriptor("1.1.1.1", "/d1/r1"),
        DFSTestUtil.getDatanodeDescriptor("2.2.2.2", "/d1/r1"),
        DFSTestUtil.getDatanodeDescriptor("3.3.3.3", "/d1/r2"),
        DFSTestUtil.getDatanodeDescriptor("4.4.4.4", "/d1/r2"),
        DFSTestUtil.getDatanodeDescriptor("5.5.5.5", "/d1/r2"),
        DFSTestUtil.getDatanodeDescriptor("6.6.6.6", "/d2/r3"),
        DFSTestUtil.getDatanodeDescriptor("7.7.7.7", "/d2/r3"),
        DFSTestUtil.getDatanodeDescriptor("8.8.8.8", "/d2/r3"),
        DFSTestUtil.getDatanodeDescriptor("9.9.9.9", "/d3/r1"),
        DFSTestUtil.getDatanodeDescriptor("10.10.10.10", "/d3/r1"),
        DFSTestUtil.getDatanodeDescriptor("11.11.11.11", "/d3/r1"),
        DFSTestUtil.getDatanodeDescriptor("12.12.12.12", "/d3/r2"),
        DFSTestUtil.getDatanodeDescriptor("13.13.13.13", "/d3/r2"),
        DFSTestUtil.getDatanodeDescriptor("14.14.14.14", "/d4/r1"),
        DFSTestUtil.getDatanodeDescriptor("15.15.15.15", "/d4/r1"),
        DFSTestUtil.getDatanodeDescriptor("16.16.16.16", "/d4/r1"),
        DFSTestUtil.getDatanodeDescriptor("17.17.17.17", "/d4/r1"),
        DFSTestUtil.getDatanodeDescriptor("18.18.18.18", "/d4/r1"),
        DFSTestUtil.getDatanodeDescriptor("19.19.19.19", "/d4/r1"),
        DFSTestUtil.getDatanodeDescriptor("20.20.20.20", "/d4/r1"),
    };
    for (int i = 0; i < dataNodes.length; i++) {
      cluster.add(dataNodes[i]);
    }
    dataNodes[9].setDecommissioned();
    dataNodes[10].setDecommissioned();
  }

  @Test
  public void testContains() throws Exception {
    DatanodeDescriptor nodeNotInMap =
      DFSTestUtil.getDatanodeDescriptor("8.8.8.8", "/d2/r4");
    for (int i=0; i < dataNodes.length; i++) {
      assertTrue(cluster.contains(dataNodes[i]));
    }
    assertFalse(cluster.contains(nodeNotInMap));
  }

  @Test
  public void testNumOfChildren() throws Exception {
    assertEquals(cluster.getNumOfLeaves(), dataNodes.length);
  }

  @Test
  public void testCreateInvalidTopology() throws Exception {
    NetworkTopology invalCluster =
        NetworkTopology.getInstance(new Configuration());
    DatanodeDescriptor invalDataNodes[] = new DatanodeDescriptor[] {
        DFSTestUtil.getDatanodeDescriptor("1.1.1.1", "/d1/r1"),
        DFSTestUtil.getDatanodeDescriptor("2.2.2.2", "/d1/r1"),
        DFSTestUtil.getDatanodeDescriptor("3.3.3.3", "/d1")
    };
    invalCluster.add(invalDataNodes[0]);
    invalCluster.add(invalDataNodes[1]);
    try {
      invalCluster.add(invalDataNodes[2]);
      fail("expected InvalidTopologyException");
    } catch (NetworkTopology.InvalidTopologyException e) {
      assertTrue(e.getMessage().startsWith("Failed to add "));
      assertTrue(e.getMessage().contains(
          "You cannot have a rack and a non-rack node at the same " +
          "level of the network topology."));
    }
  }

  @Test
  public void testRacks() throws Exception {
    assertEquals(cluster.getNumOfRacks(), 6);
    assertTrue(cluster.isOnSameRack(dataNodes[0], dataNodes[1]));
    assertFalse(cluster.isOnSameRack(dataNodes[1], dataNodes[2]));
    assertTrue(cluster.isOnSameRack(dataNodes[2], dataNodes[3]));
    assertTrue(cluster.isOnSameRack(dataNodes[3], dataNodes[4]));
    assertFalse(cluster.isOnSameRack(dataNodes[4], dataNodes[5]));
    assertTrue(cluster.isOnSameRack(dataNodes[5], dataNodes[6]));
  }

  @Test
  public void testGetDistance() throws Exception {
    assertEquals(cluster.getDistance(dataNodes[0], dataNodes[0]), 0);
    assertEquals(cluster.getDistance(dataNodes[0], dataNodes[1]), 2);
    assertEquals(cluster.getDistance(dataNodes[0], dataNodes[3]), 4);
    assertEquals(cluster.getDistance(dataNodes[0], dataNodes[6]), 6);
    // verify the distance is zero as long as two nodes have the same path.
    // They don't need to refer to the same object.
    NodeBase node1 = new NodeBase(dataNodes[0].getHostName(),
        dataNodes[0].getNetworkLocation());
    NodeBase node2 = new NodeBase(dataNodes[0].getHostName(),
        dataNodes[0].getNetworkLocation());
    assertEquals(0, cluster.getDistance(node1, node2));
    // verify the distance can be computed by path.
    // They don't need to refer to the same object or parents.
    NodeBase node3 = new NodeBase(dataNodes[3].getHostName(),
        dataNodes[3].getNetworkLocation());
    NodeBase node4 = new NodeBase(dataNodes[6].getHostName(),
        dataNodes[6].getNetworkLocation());
    assertEquals(0, NetworkTopology.getDistanceByPath(node1, node2));
    assertEquals(4, NetworkTopology.getDistanceByPath(node2, node3));
    assertEquals(6, NetworkTopology.getDistanceByPath(node2, node4));
  }

  @Test
  public void testSortByDistance() throws Exception {
    DatanodeDescriptor[] testNodes = new DatanodeDescriptor[3];

    // array contains both local node & local rack node
    testNodes[0] = dataNodes[1];
    testNodes[1] = dataNodes[2];
    testNodes[2] = dataNodes[0];
    cluster.setRandomSeed(0xDEADBEEF);
    cluster.sortByDistance(dataNodes[0], testNodes, testNodes.length);
    assertTrue(testNodes[0] == dataNodes[0]);
    assertTrue(testNodes[1] == dataNodes[1]);
    assertTrue(testNodes[2] == dataNodes[2]);

    // array contains both local node & local rack node & decommissioned node
    DatanodeDescriptor[] dtestNodes = new DatanodeDescriptor[5];
    dtestNodes[0] = dataNodes[8];
    dtestNodes[1] = dataNodes[12];
    dtestNodes[2] = dataNodes[11];
    dtestNodes[3] = dataNodes[9];
    dtestNodes[4] = dataNodes[10];
    cluster.setRandomSeed(0xDEADBEEF);
    cluster.sortByDistance(dataNodes[8], dtestNodes, dtestNodes.length - 2);
    assertTrue(dtestNodes[0] == dataNodes[8]);
    assertTrue(dtestNodes[1] == dataNodes[11]);
    assertTrue(dtestNodes[2] == dataNodes[12]);
    assertTrue(dtestNodes[3] == dataNodes[9]);
    assertTrue(dtestNodes[4] == dataNodes[10]);

    // array contains local node
    testNodes[0] = dataNodes[1];
    testNodes[1] = dataNodes[3];
    testNodes[2] = dataNodes[0];
    cluster.setRandomSeed(0xDEADBEEF);
    cluster.sortByDistance(dataNodes[0], testNodes, testNodes.length);
    assertTrue(testNodes[0] == dataNodes[0]);
    assertTrue(testNodes[1] == dataNodes[1]);
    assertTrue(testNodes[2] == dataNodes[3]);

    // array contains local rack node
    testNodes[0] = dataNodes[5];
    testNodes[1] = dataNodes[3];
    testNodes[2] = dataNodes[1];
    cluster.setRandomSeed(0xDEADBEEF);
    cluster.sortByDistance(dataNodes[0], testNodes, testNodes.length);
    assertTrue(testNodes[0] == dataNodes[1]);
    assertTrue(testNodes[1] == dataNodes[3]);
    assertTrue(testNodes[2] == dataNodes[5]);

    // array contains local rack node which happens to be in position 0
    testNodes[0] = dataNodes[1];
    testNodes[1] = dataNodes[5];
    testNodes[2] = dataNodes[3];
    cluster.setRandomSeed(0xDEADBEEF);
    cluster.sortByDistance(dataNodes[0], testNodes, testNodes.length);
    assertTrue(testNodes[0] == dataNodes[1]);
    assertTrue(testNodes[1] == dataNodes[3]);
    assertTrue(testNodes[2] == dataNodes[5]);

    // Same as previous, but with a different random seed to test randomization
    testNodes[0] = dataNodes[1];
    testNodes[1] = dataNodes[5];
    testNodes[2] = dataNodes[3];
    cluster.setRandomSeed(0xDEAD);
    cluster.sortByDistance(dataNodes[0], testNodes, testNodes.length);
    assertTrue(testNodes[0] == dataNodes[1]);
    assertTrue(testNodes[1] == dataNodes[3]);
    assertTrue(testNodes[2] == dataNodes[5]);

    // Array of just rack-local nodes
    // Expect a random first node
    DatanodeDescriptor first = null;
    boolean foundRandom = false;
    for (int i=5; i<=7; i++) {
      testNodes[0] = dataNodes[5];
      testNodes[1] = dataNodes[6];
      testNodes[2] = dataNodes[7];
      cluster.sortByDistance(dataNodes[i], testNodes, testNodes.length);
      if (first == null) {
        first = testNodes[0];
      } else {
        if (first != testNodes[0]) {
          foundRandom = true;
          break;
        }
      }
    }
    assertTrue("Expected to find a different first location", foundRandom);

    // Array of just remote nodes
    // Expect random first node
    first = null;
    for (int i = 1; i <= 4; i++) {
      testNodes[0] = dataNodes[13];
      testNodes[1] = dataNodes[14];
      testNodes[2] = dataNodes[15];
      cluster.sortByDistance(dataNodes[i], testNodes, testNodes.length);
      if (first == null) {
        first = testNodes[0];
      } else {
        if (first != testNodes[0]) {
          foundRandom = true;
          break;
        }
      }
    }
    assertTrue("Expected to find a different first location", foundRandom);

    //Reader is not a datanode, but is in one of the datanode's rack.
    testNodes[0] = dataNodes[0];
    testNodes[1] = dataNodes[5];
    testNodes[2] = dataNodes[8];
    Node rackClient = new NodeBase("/d3/r1/25.25.25");
    cluster.setRandomSeed(0xDEADBEEF);
    cluster.sortByDistance(rackClient, testNodes, testNodes.length);
    assertTrue(testNodes[0] == dataNodes[8]);
    assertTrue(testNodes[1] == dataNodes[5]);
    assertTrue(testNodes[2] == dataNodes[0]);

    //Reader is not a datanode , but is in one of the datanode's data center.
    testNodes[0] = dataNodes[8];
    testNodes[1] = dataNodes[5];
    testNodes[2] = dataNodes[0];
    Node dcClient = new NodeBase("/d1/r2/25.25.25");
    cluster.setRandomSeed(0xDEADBEEF);
    cluster.sortByDistance(dcClient, testNodes, testNodes.length);
    assertTrue(testNodes[0] == dataNodes[0]);
    assertTrue(testNodes[1] == dataNodes[5]);
    assertTrue(testNodes[2] == dataNodes[8]);

  }

  @Test
  public void testRemove() throws Exception {
    for(int i=0; i<dataNodes.length; i++) {
      cluster.remove(dataNodes[i]);
    }
    for(int i=0; i<dataNodes.length; i++) {
      assertFalse(cluster.contains(dataNodes[i]));
    }
    assertEquals(0, cluster.getNumOfLeaves());
    assertEquals(0, cluster.clusterMap.getChildren().size());
    for(int i=0; i<dataNodes.length; i++) {
      cluster.add(dataNodes[i]);
    }
  }

  /**
   * This picks a large number of nodes at random in order to ensure coverage
   *
   * @param numNodes the number of nodes
   * @param excludedScope the excluded scope
   * @return the frequency that nodes were chosen
   */
  private Map<Node, Integer> pickNodesAtRandom(int numNodes,
      String excludedScope, Collection<Node> excludedNodes) {
    Map<Node, Integer> frequency = new HashMap<Node, Integer>();
    for (DatanodeDescriptor dnd : dataNodes) {
      frequency.put(dnd, 0);
    }

    for (int j = 0; j < numNodes; j++) {
      Node random = cluster.chooseRandom(excludedScope, excludedNodes);
      if (random != null) {
        frequency.put(random, frequency.get(random) + 1);
      }
    }
    return frequency;
  }

  /**
   * This test checks that chooseRandom works for an excluded node.
   */
  @Test
  public void testChooseRandomExcludedNode() {
    String scope = "~" + NodeBase.getPath(dataNodes[0]);
    Map<Node, Integer> frequency = pickNodesAtRandom(100, scope, null);

    for (Node key : dataNodes) {
      // all nodes except the first should be more than zero
      assertTrue(frequency.get(key) > 0 || key == dataNodes[0]);
    }
  }

  /**
   * This test checks that chooseRandom works for an excluded rack.
   */
  @Test
  public void testChooseRandomExcludedRack() {
    Map<Node, Integer> frequency = pickNodesAtRandom(100, "~" + "/d2", null);
    // all the nodes on the second rack should be zero
    for (int j = 0; j < dataNodes.length; j++) {
      int freq = frequency.get(dataNodes[j]);
      if (dataNodes[j].getNetworkLocation().startsWith("/d2")) {
        assertEquals(0, freq);
      } else {
        assertTrue(freq > 0);
      }
    }
  }

  /**
   * This test checks that chooseRandom works for a list of excluded nodes.
   */
  @Test
  public void testChooseRandomExcludedNodeList() {
    String scope = "~" + NodeBase.getPath(dataNodes[0]);
    Set<Node> excludedNodes = new HashSet<>();
    excludedNodes.add(dataNodes[3]);
    excludedNodes.add(dataNodes[5]);
    excludedNodes.add(dataNodes[7]);
    excludedNodes.add(dataNodes[9]);
    excludedNodes.add(dataNodes[13]);
    excludedNodes.add(dataNodes[18]);
    Map<Node, Integer> frequency = pickNodesAtRandom(100, scope, excludedNodes);

    assertEquals("dn[3] should be excluded", 0,
        frequency.get(dataNodes[3]).intValue());
    assertEquals("dn[5] should be exclude18d", 0,
        frequency.get(dataNodes[5]).intValue());
    assertEquals("dn[7] should be excluded", 0,
        frequency.get(dataNodes[7]).intValue());
    assertEquals("dn[9] should be excluded", 0,
        frequency.get(dataNodes[9]).intValue());
    assertEquals("dn[13] should be excluded", 0,
        frequency.get(dataNodes[13]).intValue());
    assertEquals("dn[18] should be excluded", 0,
        frequency.get(dataNodes[18]).intValue());
    for (Node key : dataNodes) {
      if (excludedNodes.contains(key)) {
        continue;
      }
      // all nodes except the first should be more than zero
      assertTrue(frequency.get(key) > 0 || key == dataNodes[0]);
    }
  }

  /**
   * This test checks that chooseRandom works when all nodes are excluded.
   */
  @Test
  public void testChooseRandomExcludeAllNodes() {
    String scope = "~" + NodeBase.getPath(dataNodes[0]);
    Set<Node> excludedNodes = new HashSet<>();
    for (int i = 0; i < dataNodes.length; i++) {
      excludedNodes.add(dataNodes[i]);
    }
    Map<Node, Integer> frequency = pickNodesAtRandom(100, scope, excludedNodes);
    for (Node key : dataNodes) {
      // all nodes except the first should be more than zero
      assertTrue(frequency.get(key) == 0);
    }
  }

  @Test(timeout=180000)
  public void testInvalidNetworkTopologiesNotCachedInHdfs() throws Exception {
    // start a cluster
    Configuration conf = new HdfsConfiguration();
    MiniDFSCluster cluster = null;
    try {
      // bad rack topology
      String racks[] = { "/a/b", "/c" };
      String hosts[] = { "foo1.example.com", "foo2.example.com" };
      cluster = new MiniDFSCluster.Builder(conf).numDataNodes(2).
          racks(racks).hosts(hosts).build();
      cluster.waitActive();

      NamenodeProtocols nn = cluster.getNameNodeRpc();
      Assert.assertNotNull(nn);

      // Wait for one DataNode to register.
      // The other DataNode will not be able to register up because of the rack mismatch.
      DatanodeInfo[] info;
      while (true) {
        info = nn.getDatanodeReport(DatanodeReportType.LIVE);
        Assert.assertFalse(info.length == 2);
        if (info.length == 1) {
          break;
        }
        Thread.sleep(1000);
      }
      // Set the network topology of the other node to the match the network
      // topology of the node that came up.
      int validIdx = info[0].getHostName().equals(hosts[0]) ? 0 : 1;
      int invalidIdx = validIdx == 1 ? 0 : 1;
      StaticMapping.addNodeToRack(hosts[invalidIdx], racks[validIdx]);
      LOG.info("datanode " + validIdx + " came up with network location " +
        info[0].getNetworkLocation());

      // Restart the DN with the invalid topology and wait for it to register.
      cluster.restartDataNode(invalidIdx);
      Thread.sleep(5000);
      while (true) {
        info = nn.getDatanodeReport(DatanodeReportType.LIVE);
        if (info.length == 2) {
          break;
        }
        if (info.length == 0) {
          LOG.info("got no valid DNs");
        } else if (info.length == 1) {
          LOG.info("got one valid DN: " + info[0].getHostName() +
              " (at " + info[0].getNetworkLocation() + ")");
        }
        Thread.sleep(1000);
      }
      Assert.assertEquals(info[0].getNetworkLocation(),
                          info[1].getNetworkLocation());
    } finally {
      if (cluster != null) {
        cluster.shutdown();
      }
    }
  }

}


text:
<!DOCTYPE html>

	<wicket:panel>

<wicket:message key="delete.label"></wicket:message>

		<form class="form-vertical" wicket:id="form">

<wicket:message key="delete.warning"></wicket:message>

				<input type="submit" wicket:id="submit" wicket:message="value:button.deleteitem" />
				<input type="submit" wicket:id="cancel" wicket:message="value:button.cancel" />

		</form>

	</wicket:panel>

redpajama_set_name: RedPajamaGithub


text: see https://plugins.jetbrains.com/plugin/9585-settings-enforcer


text:
var FCKKeystrokeHandler = function( cancelCtrlDefaults )
{
	this.Keystrokes = new Object() ;
	this.CancelCtrlDefaults = ( cancelCtrlDefaults !== false ) ;
}

/*
 * Listen to keystroke events in an element or DOM document object.
 *		@target: The element or document to listen to keystroke events.
 */
FCKKeystrokeHandler.prototype.AttachToElement = function( target )
{
	// For newer browsers, it is enough to listen to the keydown event only.
	// Some browsers instead, don't cancel key events in the keydown, but in the
	// keypress. So we must do a longer trip in those cases.
	FCKTools.AddEventListenerEx( target, 'keydown', _FCKKeystrokeHandler_OnKeyDown, this ) ;
	if ( FCKBrowserInfo.IsGecko10 || FCKBrowserInfo.IsOpera || ( FCKBrowserInfo.IsGecko && FCKBrowserInfo.IsMac ) )
		FCKTools.AddEventListenerEx( target, 'keypress', _FCKKeystrokeHandler_OnKeyPress, this ) ;
}

/*
 * Sets a list of keystrokes. It can receive either a single array or "n"
 * arguments, each one being an array of 1 or 2 elemenst. The first element
 * is the keystroke combination, and the second is the value to assign to it.
 * If the second element is missing, the keystroke definition is removed.
 */
FCKKeystrokeHandler.prototype.SetKeystrokes = function()
{
	// Look through the arguments.
	for ( var i = 0 ; i < arguments.length ; i++ )
	{
		var keyDef = arguments[i] ;

		// If the configuration for the keystrokes is missing some element or has any extra comma
		// this item won't be valid, so skip it and keep on processing.
		if ( !keyDef )
			continue ;

		if ( typeof( keyDef[0] ) == 'object' )		// It is an array with arrays defining the keystrokes.
			this.SetKeystrokes.apply( this, keyDef ) ;
		else
		{
			if ( keyDef.length == 1 )		// If it has only one element, remove the keystroke.
				delete this.Keystrokes[ keyDef[0] ] ;
			else							// Otherwise add it.
				this.Keystrokes[ keyDef[0] ] = keyDef[1] === true ? true : keyDef ;
		}
	}
}

function _FCKKeystrokeHandler_OnKeyDown( ev, keystrokeHandler )
{
	// Get the key code.
	var keystroke = ev.keyCode || ev.which ;

	// Combine it with the CTRL, SHIFT and ALT states.
	var keyModifiers = 0 ;

	if ( ev.ctrlKey || ev.metaKey )
		keyModifiers += CTRL ;

	if ( ev.shiftKey )
		keyModifiers += SHIFT ;

	if ( ev.altKey )
		keyModifiers += ALT ;

	var keyCombination = keystroke + keyModifiers ;

	var cancelIt = keystrokeHandler._CancelIt = false ;

	// Look for its definition availability.
	var keystrokeValue = keystrokeHandler.Keystrokes[ keyCombination ] ;

//	FCKDebug.Output( 'KeyDown: ' + keyCombination + ' - Value: ' + keystrokeValue ) ;

	// If the keystroke is defined
	if ( keystrokeValue )
	{
		// If the keystroke has been explicitly set to "true" OR calling the
		// "OnKeystroke" event, it doesn't return "true", the default behavior
		// must be preserved.
		if ( keystrokeValue === true || !( keystrokeHandler.OnKeystroke && keystrokeHandler.OnKeystroke.apply( keystrokeHandler, keystrokeValue ) ) )
			return true ;

		cancelIt = true ;
	}

	// By default, it will cancel all combinations with the CTRL key only (except positioning keys).
	if ( cancelIt || ( keystrokeHandler.CancelCtrlDefaults && keyModifiers == CTRL && ( keystroke < 33 || keystroke > 40 ) ) )
	{
		keystrokeHandler._CancelIt = true ;

		if ( ev.preventDefault )
			return ev.preventDefault() ;

		ev.returnValue = false ;
		ev.cancelBubble = true ;
		return false ;
	}

	return true ;
}

function _FCKKeystrokeHandler_OnKeyPress( ev, keystrokeHandler )
{
	if ( keystrokeHandler._CancelIt )
	{
//		FCKDebug.Output( 'KeyPress Cancel', 'Red') ;

		if ( ev.preventDefault )
			return ev.preventDefault() ;

		return false ;
	}

	return true ;
}


text:
#ifndef _GETDEF_H
#define _GETDEF_H

/* getdef.c */
extern bool getdef_bool (const char *);
extern long getdef_long (const char *, long);
extern int getdef_num (const char *, int);
extern unsigned long getdef_ulong (const char *, unsigned long);
extern unsigned int getdef_unum (const char *, unsigned int);
extern /*@observer@*/ /*@null@*/const char *getdef_str (const char *);
extern int putdef_str (const char *, const char *);

/* default UMASK value if not specified in /etc/login.defs */
#define		GETDEF_DEFAULT_UMASK	022

#endif				/* _GETDEF_H */


text:
<!DOCTYPE html>

Test changing a spanner that follows column content to a regular block.

You should see the word 'PASS' below, with large letter spacing:

PASS


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const mongoose = require("mongoose");
const List_1 = require("../functional/List");
const Future_1 = require("../functional/Future");
const IOMap_1 = require("../functional/IOMap");
//change all to use promise no callback
class Table {
    constructor(m) {
        this.model = m;
    }
    exec(query, alwaysOne = true) {
        const exists = res => {
            if (!res)
                return false;
            else if (res.length) {
                return res.length > 0;
            }
            else
                return true;
        };
        return new Future_1.Future((resolve, reject) => {
            query.exec((err, res) => {
                if (err)
                    reject(err.message);
                else if (alwaysOne && !exists(res))
                    reject("No entries found");
                else
                    resolve(res);
            });
        });
    }
    get(query) {
        return this.model.find(query);
    }
    getByIDs(ids) {
        return this.get({ _id: { $in: ids } });
    }
    getAll() {
        return this.get({});
    }
    getOne(query) {
        return this.model.findOne(query);
    }
    getByID(id) {
        return this.getOne({ _id: id });
    }
    updateOne(id, update) {
        return this.exec(this.getByID(id)).flatMap(a => {
            update(a);
            return a.save();
        });
    }
    update(ids, update) {
        return this.exec(this.getByIDs(ids)).flatMap(a => {
            return IOMap_1.IOMap.traverse(List_1.List.apply(a), IOMap_1.IOMap.apply).run(a2 => {
                update(a2);
                return Future_1.Future.lift(a2.save());
            }).map(la => la.toArray());
        });
    }
    create(a) {
        return Future_1.Future.lift(this.model.create(a));
    }
    map(query, f) {
        return this.exec(query, true).map(f);
    }
}
exports.Table = Table;
var Tables;
(function (Tables) {
    Tables.user = new mongoose.Schema({
        _id: String,
        name: String,
        surename: String,
        groups: [{
                group: refrence("Group"),
                files: [{
                        final: Boolean,
                        file: refrence("File")
                    }],
                active: { type: Boolean, default: true }
            }],
        admin: Boolean
    });
    Tables.assignment = new mongoose.Schema({
        files: [refrence("File")],
        due: Date,
        group: refrence("Group"),
        name: String,
        link: String,
        typ: String,
        project: String
    });
    Tables.group = new mongoose.Schema({
        name: String,
        assignments: [refrence("Assignment")],
        students: [refrence("User")],
        admins: [refrence("User")],
        start: Date,
        end: Date
    });
    Tables.file = new mongoose.Schema({
        assignment: refrence("Assignment"),
        timestamp: Date,
        students: [refrence("User")],
        autograder: [{
                input: Object,
                success: Boolean,
                message: String
            }],
        notes: String,
        feedback: String,
        urls: [String],
        name: String
    });
    function refrence(to) {
        return { type: String, ref: to };
    }
    Tables.User = mongoose.model('User', Tables.user);
    Tables.Assignment = mongoose.model('Assignment', Tables.assignment);
    Tables.File = mongoose.model('File', Tables.file);
    Tables.Group = mongoose.model('Group', Tables.group);
})(Tables = exports.Tables || (exports.Tables = {}));


text:
// Licensed to Cloudera, Inc. under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  Cloudera, Inc. licenses this file
// to you 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.cloudera.csd.validation.references.components;

import com.cloudera.csd.validation.references.DescriptorPath;
import com.cloudera.csd.validation.references.annotations.Named;
import com.cloudera.csd.validation.references.annotations.Referenced;
import com.google.common.base.Joiner;
import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Set;

import javax.validation.ElementKind;

/**
 * An implementation of a DescriptorPath
 */
public class DescriptorPathImpl implements DescriptorPath {

  private final LinkedList<DescriptorNodeImpl> list = Lists.newLinkedList();
  private static final Joiner JOINER = Joiner.on(".");

  public static class DescriptorNodeImpl implements DescriptorPath.DescriptorNode {

    private final String name;
    private final boolean iterable;
    private final Integer index;
    private final Object key;
    private final ElementKind kind;

    public DescriptorNodeImpl(String name,
                              boolean iterable,
                              Integer index,
                              Object key,
                              ElementKind kind) {
      this.name = name;
      this.iterable = iterable;
      this.index = index;
      this.key = key;
      this.kind = kind;
    }

    @Override
    public String getName() {
      return this.name;
    }

    @Override
    public boolean isInIterable() {
      return this.iterable;
    }

    @Override
    public Integer getIndex() {
      return this.index;
    }

    @Override
    public Object getKey() {
      return this.key;
    }

    @Override
    public ElementKind getKind() {
      return this.kind;
    }

    @Override
    public <T extends Node> T as(Class<T> nodeType) {
      return nodeType.cast(this);
    }

    @Override
    public String toString() {
      return this.name;
    }

    @Override
    public boolean equals(Object other) {
      if (other instanceof DescriptorNodeImpl) {
        DescriptorNodeImpl o = (DescriptorNodeImpl)other;
        return Objects.equal(this.name, o.name);
      }
      return false;
    }

    @Override
    public int hashCode() {
      return this.name.hashCode();
    }
  }

  public static class PropertyNode extends DescriptorNodeImpl implements PropertyDescriptorNode {
    private final Method method;
    public PropertyNode(String name,
                        boolean iterable,
                        Integer index,
                        Method method) {
      super(name, iterable, index, null, ElementKind.PROPERTY);
      this.method = method;
    }

    @Override
    public Method getMethod() {
      return this.method;
    }

    @Override
    public boolean equals(Object other) {
      if (other instanceof PropertyNode) {
        if (super.equals(other)) {
          PropertyNode oProperty = (PropertyNode)other;
          return Objects.equal(this.method, oProperty.method);
        }
      }
      return false;
    }

    @Override
    public int hashCode() {
      return Objects.hashCode(super.hashCode(), this.method.hashCode());
    }
  }

  public static class BeanNode extends DescriptorNodeImpl implements BeanDescriptorNode {
    private final boolean isNamed;
    private final Object bean;

    public BeanNode(String name,
                    Object key,
                    Object bean,
                    boolean isNamed) {
      super(name, false, null, key, ElementKind.BEAN);
      this.isNamed = isNamed;
      this.bean = bean;
    }

    @Override
    public Object getBean() {
      return this.bean;
    }

    @Override
    public boolean isNamed() {
      return this.isNamed;
    }

    @Override
    public boolean equals(Object other) {
      if (other instanceof BeanNode) {
        if (super.equals(other)) {
          BeanNode o = (BeanNode)other;
          return Objects.equal(this.bean, o.bean);
        }
      }
      return false;
    }

    @Override
    public int hashCode() {
      return Objects.hashCode(super.hashCode(), this.bean.hashCode());
    }
  }

  @Override
  public DescriptorNode getHeadNode() {
    if (this.list.size() == 0) {
      return null;
    }
    return this.list.getLast();
  }

  @Override
  public DescriptorNode getTailNode() {
    if (this.list.size() == 0) {
      return null;
    }
    return this.list.getFirst();
  }

  @Override
  public DescriptorPathImpl removeFromHead() {
    DescriptorPathImpl newPath = makeCopy();
    newPath.list.removeLast();
    return newPath;
  }

  @Override
  public Iterator<Node> iterator() {
    return ImmutableList.<Node>copyOf(list).iterator();
  }

  /**
   * Given a method, creates and adds a property node to the path.
   *
   * @param method the method
   * @param isIterable true if it is an iterable
   * @return a new path
   */
  public DescriptorPathImpl addPropertyNode(Method method, boolean isIterable) {
    Preconditions.checkNotNull(method);
    String name = ReflectionHelper.propertyNameOfGetter(method);
    return addToHead(new PropertyNode(name, isIterable, null, method));
  }

  /**
   * Given a bean object, creates and adds a bean node to the path.
   *
   * @param obj the bean.
   * @return a new path.
   */
  public DescriptorPathImpl addBeanNode(Object obj) {
    Preconditions.checkNotNull(obj);
    String[] names = new String[]{obj.getClass().getSimpleName()};
    Named named = ReflectionHelper.findAnnotation(obj.getClass(), Named.class);
    if (named != null) {
      names = new String[]{ReflectionHelper.propertyValueByName(obj, named.value(), String.class)};
    }
    // If there is a @Referenced annotation and it has a hardcoded "as" value,
    // use that name instead.
    Referenced referenced = ReflectionHelper.findAnnotation(obj.getClass(), Referenced.class);
    if ((referenced != null) && (referenced.as().length != 0)) {
      names = referenced.as();
    }
    return addToHead(new BeanNode(
        names.length == 1 ? names[0] : Arrays.toString(names),
        null, obj, (named != null)));
  }

  @Override
  public DescriptorPathImpl onlyInclude(ElementKind... whitelist) {
    Set<ElementKind> kinds = ImmutableSet.copyOf(whitelist);
    DescriptorPathImpl newPath = new DescriptorPathImpl();
    for (DescriptorNodeImpl node : this.list) {
      if (kinds.contains(node.getKind())) {
        newPath.list.add(node);
      }
    }
    return newPath;
  }

  @Override
  public boolean contains(String name, ElementKind kind) {
     for (DescriptorNodeImpl node : this.list) {
      if (kind.equals(node.getKind()) && node.getName().equals(name)) {
        return true;
      }
    }
    return false;
  }

  @Override
  public String toString() {
    return JOINER.join(list);
  }

  @Override
  public boolean equals(Object o) {
    if (o instanceof DescriptorPathImpl) {
      DescriptorPathImpl other = (DescriptorPathImpl)o;
      return Objects.equal(this.list, other.list);
    }
    return false;
  }

  @Override
  public int hashCode() {
    return this.list.hashCode();
  }

  private DescriptorPathImpl addToHead(DescriptorNodeImpl node) {
    DescriptorPathImpl newPath = makeCopy();
    newPath.list.add(node);
    return newPath;
  }

  private DescriptorPathImpl makeCopy() {
    DescriptorPathImpl newPath = new DescriptorPathImpl();
    newPath.list.addAll(this.list);
    return newPath;
  }

}


text:
.PHONY: test coverage

test:
	./node_modules/.bin/mocha --recursive --timeout 10000 --exit ./test/unit ./test/integration

test-bail:
	./node_modules/.bin/mocha --bail --recursive --timeout 10000 ./test/unit ./test/integration

test-integration:
	./node_modules/.bin/mocha --recursive --timeout 10000 ./test/integration

test-unit:
	./node_modules/.bin/mocha --recursive ./test/unit/

lint:
	./node_modules/.bin/eslint ./src

update-players:
	node ./scripts/players.js

update-teams:
	node ./scripts/teams.js

preversion:
	@make update-players
	@make update-teams
	@make lint


text:
package edu.galileo.android.tipcalc;

import android.app.Application;
import android.test.ApplicationTestCase;

/**
 * Testing Fundamentals
 */
public class ApplicationTest extends ApplicationTestCase<Application> {
    public ApplicationTest() {
        super(Application.class);
    }
}


text:
package gov.sandia.cognition.statistics.distribution;

import gov.sandia.cognition.annotation.PublicationReference;
import gov.sandia.cognition.annotation.PublicationType;
import gov.sandia.cognition.math.NumberAverager;
import gov.sandia.cognition.math.matrix.Vector;
import gov.sandia.cognition.math.matrix.VectorFactory;
import gov.sandia.cognition.statistics.AbstractClosedFormSmoothUnivariateDistribution;
import gov.sandia.cognition.statistics.DistributionEstimator;
import gov.sandia.cognition.statistics.DistributionWeightedEstimator;
import gov.sandia.cognition.statistics.EstimableDistribution;
import gov.sandia.cognition.statistics.InvertibleCumulativeDistributionFunction;
import gov.sandia.cognition.statistics.UnivariateProbabilityDensityFunction;
import gov.sandia.cognition.statistics.SmoothCumulativeDistributionFunction;
import gov.sandia.cognition.util.AbstractCloneableSerializable;
import gov.sandia.cognition.util.WeightedValue;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Random;

/**
 * A Laplace distribution, sometimes called a double exponential distribution.
 * This distribution arrises when evaluating the difference between two iid
 * exponential random variables, or when sampling Brownian motion at
 * exponentially distributed time steps.
 * @author Kevin R. Dixon
 * @since 3.0
 */
@PublicationReference(
    author="Wikipedia",
    title="Laplace distribution",
    type=PublicationType.WebPage,
    year=2009,
    url="http://en.wikipedia.org/wiki/Laplace_distribution"
)
public class LaplaceDistribution
    extends AbstractClosedFormSmoothUnivariateDistribution
    implements EstimableDistribution<Double,LaplaceDistribution>
{

    /**
     * Default mean, {@value}.
     */
    public static final double DEFAULT_MEAN = 0.0;

    /**
     * Default scale, {@value}.
     */
    public static final double DEFAULT_SCALE = 1.0;

    /**
     * Mean of the distribution
     */
    protected double mean;

    /**
     * Scale factor of the distribution, must be greater than zero.
     */
    protected double scale;

    /**
     * Creates a new instance of LaplaceDistribution
     */
    public LaplaceDistribution()
    {
        this( DEFAULT_MEAN, DEFAULT_SCALE );
    }

    /**
     * Creates a new instance of LaplaceDistribution
     * @param mean
     * Mean of the distribution
     * @param scale
     * Scale factor of the distribution, must be greater than zero.
     */
    public LaplaceDistribution(
        final double mean,
        final double scale )
    {
        super();
        this.setMean(mean);
        this.setScale(scale);
    }

    /**
     * Copy Constructor
     * @param other LaplaceDistribution to copy
     */
    public LaplaceDistribution(
        final LaplaceDistribution other )
    {
        this( other.getMean(), other.getScale() );
    }

    @Override
    public LaplaceDistribution clone()
    {
        return (LaplaceDistribution) super.clone();
    }

    @Override
    public Double getMean()
    {
        return this.mean;
    }

    @Override
    public double getMeanAsDouble()
    {
        return this.mean;
    }

    /**
     * Setter for mean
     * @param mean
     * Mean of the distribution
     */
    public void setMean(
        final double mean)
    {
        this.mean = mean;
    }

    /**
     * Getter for scale
     * @return
     * Scale factor of the distribution, must be greater than zero.
     */
    public double getScale()
    {
        return this.scale;
    }

    /**
     * Setter for scale
     * @param scale
     * Scale factor of the distribution, must be greater than zero.
     */
    public void setScale(
        final double scale)
    {
        if( scale <= 0.0 )
        {
            throw new IllegalArgumentException( "scale must be > 0.0" );
        }
        this.scale = scale;
    }

    @Override
    public double sampleAsDouble(
        final Random random)
    {
        final double p = random.nextDouble();
        return LaplaceDistribution.CDF.inverse(this, p);
    }

    @Override
    public void sampleInto(
        final Random random,
        final double[] output,
        final int start,
        final int length)
    {
        final int end = start + length;
        for (int i = start; i < end; i++)
        {
            output[i] = this.sampleAsDouble(random);
        }
    }

    @Override
    public Vector convertToVector()
    {
        return VectorFactory.getDefault().copyValues(
            this.getMean(), this.getScale() );
    }

    @Override
    public void convertFromVector(
        final Vector parameters)
    {
        parameters.assertDimensionalityEquals(2);
        this.setMean( parameters.getElement(0) );
        this.setScale( parameters.getElement(1) );
    }

    @Override
    public double getVariance()
    {
        final double b = this.getScale();
        return 2.0*b*b;
    }

    @Override
    public String toString()
    {
        return "Mean: " + this.getMean() + ", Scale: " + this.getScale();
    }

    @Override
    public LaplaceDistribution.CDF getCDF()
    {
        return new LaplaceDistribution.CDF( this );
    }

    @Override
    public LaplaceDistribution.PDF getProbabilityFunction()
    {
        return new LaplaceDistribution.PDF( this );
    }

    @Override
    public Double getMinSupport()
    {
        return Double.NEGATIVE_INFINITY;
    }

    @Override
    public Double getMaxSupport()
    {
        return Double.POSITIVE_INFINITY;
    }

    @Override
    public LaplaceDistribution.MaximumLikelihoodEstimator getEstimator()
    {
        return new LaplaceDistribution.MaximumLikelihoodEstimator();
    }

    /**
     * CDF of the Laplace distribution.
     */
    public static class CDF
        extends LaplaceDistribution
        implements SmoothCumulativeDistributionFunction,
        InvertibleCumulativeDistributionFunction<Double>
    {

        /**
         * Creates a new instance of LaplaceDistribution.CDF
         */
        public CDF()
        {
            super();
        }

        /**
         * Creates a new instance of LaplaceDistribution.CDF
         * @param mean
         * Mean of the distribution
         * @param scale
         * Scale factor of the distribution, must be greater than zero.
         */
        public CDF(
            final double mean,
            final double scale )
        {
            super(mean,scale);
        }

        /**
         * Copy Constructor
         * @param other LaplaceDistribution to copy
         */
        public CDF(
            final LaplaceDistribution other )
        {
            super( other );
        }

        @Override
        public Double evaluate(
            final Double input)
        {
            return this.evaluate(input.doubleValue());
        }

        @Override
        public double evaluateAsDouble(
            final Double input)
        {
            return this.evaluate(input.doubleValue());
        }

        @Override
        public double evaluate(
            final double input)
        {
            if( input == Double.NEGATIVE_INFINITY )
            {
                return 0.0;
            }
            else if( input == Double.POSITIVE_INFINITY )
            {
                return 1.0;
            }
            double delta = input - this.mean;
            return 0.5 * (1.0 + Math.signum(delta)*(1.0-Math.exp(-Math.abs(delta)/this.scale)));
        }

        /**
         * Computes the inverse of the CDF for the give probability.  That is,
         * find x=CDF.inverse(p) so that CDF(x)=p.
         * @param p
         * Probability to invert, must be [0,1].
         * @return
         * Finds the value of the CDF "x" so that CDF(x)=p.
         */
        @Override
        public Double inverse(
            final double p )
        {
            return inverse( this, p );
        }

        /**
         * Computes the inverse of the CDF for the give probability.  That is,
         * find x=CDF.inverse(p) so that CDF(x)=p.
         * @param laplace
         * Laplace distribution to invert.
         * @param p
         * Probability to invert, must be [0,1].
         * @return
         * Finds the value of the CDF "x" so that CDF(x)=p.
         */
        public static double inverse(
            final LaplaceDistribution laplace,
            final double p )
        {
            if( p <= 0.0 )
            {
                return laplace.getMinSupport();
            }
            else if( p >= 1.0 )
            {
                return laplace.getMaxSupport();
            }
            else
            {
                double delta = p - 0.5;
                return laplace.mean -
                    laplace.scale*Math.signum(delta)*Math.log(1.0-2.0*Math.abs(delta));
            }
        }

        @Override
        public LaplaceDistribution.CDF getCDF()
        {
            return this;
        }

        @Override
        public LaplaceDistribution.PDF getDerivative()
        {
            return this.getProbabilityFunction();
        }

        @Override
        public Double differentiate(
            final Double input)
        {
            return this.getDerivative().evaluate(input);
        }

    }

    /**
     * The PDF of a Laplace Distribution.
     */
    public static class PDF
        extends LaplaceDistribution
        implements UnivariateProbabilityDensityFunction
    {

        /**
         * Creates a new instance of LaplaceDistribution.PDF
         */
        public PDF()
        {
            super();
        }

        /**
         * Creates a new instance of LaplaceDistribution.PDF
         * @param mean
         * Mean of the distribution
         * @param scale
         * Scale factor of the distribution, must be greater than zero.
         */
        public PDF(
            final double mean,
            final double scale )
        {
            super(mean,scale);
        }

        /**
         * Copy Constructor
         * @param other LaplaceDistribution to copy
         */
        public PDF(
            final LaplaceDistribution other )
        {
            super( other );
        }

        @Override
        public double evaluate(
            final double input)
        {
            double front = 0.5 / this.scale;
            double exponent = -Math.abs(input-this.mean) / this.scale;
            return front * Math.exp(exponent);
        }

        @Override
        public Double evaluate(
            Double input)
        {
            return this.evaluate( input.doubleValue() );
        }

        @Override
        public double evaluateAsDouble(
            final Double input)
        {
            return this.evaluate(input.doubleValue());
        }

        @Override
        public double logEvaluate(
            final Double input)
        {
            return this.logEvaluate((double) input);
        }

        @Override
        public double logEvaluate(
            final double input)
        {
            final double n1 = Math.log( 0.5 / this.scale );
            final double n2 = -Math.abs(input-this.mean) / this.scale;
            return n1 + n2;
        }

        @Override
        public LaplaceDistribution.PDF getProbabilityFunction()
        {
            return this;
        }

    }

    /**
     * Estimates the ML parameters of a Laplace distribution from a
     * Collection of Numbers.
     */
    public static class MaximumLikelihoodEstimator
        extends AbstractCloneableSerializable
        implements DistributionEstimator<Double,LaplaceDistribution>
    {

        /**
         * Default constructor
         */
        public MaximumLikelihoodEstimator()
        {
            super();
        }

        @Override
        public LaplaceDistribution learn(
            final Collection<? extends Double> data)
        {

            final double mean = NumberAverager.INSTANCE.summarize(data);
            double absSum = 0.0;
            for( Double value : data )
            {
                double delta = value - mean;
                absSum += Math.abs(delta);
            }
            double scale = absSum / data.size();
            return new LaplaceDistribution( mean, scale );
        }

    }

    /**
     * Creates a UnivariateGaussian from weighted data
     */
    public static class WeightedMaximumLikelihoodEstimator
        extends AbstractCloneableSerializable
        implements DistributionWeightedEstimator<Double,LaplaceDistribution>
    {

        /**
         * Default constructor
         */
        public WeightedMaximumLikelihoodEstimator()
        {
            super();
        }

        /**
         * Creates a new instance of LaplaceDistribution using a weighted
         * Maximum Likelihood estimate based on the given data
         * @param data
         * Weighed pairs of data (first is data, second is weight) that was
         * generated by some unknown LaplaceDistribution distribution
         * @return
         * Maximum Likelihood UnivariateGaussian that generated the data
         */
        @Override
        public LaplaceDistribution learn(
            final Collection<? extends WeightedValue<? extends Double>> data )
        {

            double mean = 0.0;
            double weightSum = 0.0;
            for( WeightedValue<? extends Double> weightedValue : data )
            {
                double weight = weightedValue.getWeight();
                if( weight != 0.0 )
                {
                    double value = weightedValue.getValue().doubleValue();
                    mean += weight*value;
                    weightSum += weight;
                }
            }

            if( weightSum != 0.0 )
            {
                mean /= weightSum;
            }

            // Now compute the shape factor
            double shape = 0.0;
            for( WeightedValue<? extends Number> weightedValue : data )
            {
                double weight = weightedValue.getWeight();
                if( weight != 0.0 )
                {
                    double value = weightedValue.getValue().doubleValue();
                    double delta = value - mean;
                    shape += weight * Math.abs(delta);
                }
            }

            if( weightSum != 0.0 )
            {
                shape /= weightSum;
            }

            return new LaplaceDistribution( mean, shape );

        }

    }

}


text:
'use strict';

var path = require('path');
var webpack = require('webpack');
var FlowStatusWebpackPlugin = require('flow-status-webpack-plugin');
var EslintFriendlyFormatter = require("eslint-friendly-formatter")
var hotMiddlewareClient = 'webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000'

module.exports = {
  name: 'select-pad',
  debug: true,
  context: __dirname,
  devtool: '#source-map',
  entry: {
    index: [
        'eventsource-polyfill', // necessary for hot reloading with IE
        hotMiddlewareClient,
        './examples/index.js',
    ],
  },
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'build.js',
    publicPath: '/static/',
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin(),
    new FlowStatusWebpackPlugin()
  ],
  resolve: {
    modulesDirectories: ['node_modules', 'src'],
    extensions: ['', '.js', '.jsx', '.css'],
    root: [
      path.resolve(__dirname, 'examples'),
      path.resolve(__dirname, 'src'),
    ],
  },
  eslint: {
    formatter: EslintFriendlyFormatter
  },
  module: {
    preLoaders: [
      {
        test: /\.(js|jsx)$/,
        loader: 'eslint',
        exclude: [
          path.join(__dirname, 'node_modules'),
          path.join(__dirname, 'examples'),
          path.join(__dirname, 'lib'),
          path.join(__dirname, 'typedefs')
        ],
        include: [
          path.join(__dirname, 'src'),
        ]
      }
    ],
    loaders: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        include: [
          path.resolve('src'),
          path.resolve('examples'),
        ],
        loader: 'babel',
        query: {
          cacheDirectory: true,
          presets: ['react', 'es2015', 'stage-1',],
          plugins: ['transform-runtime', 'transform-flow-strip-types']
        },
        env: {
          development: {
            presets: ['react-hmre']
          }
        }
      }
    ],
    postLoaders: [],
  }
}


text:
import { Dimension } from 'vs/base/browser/dom';
import { Event } from 'vs/base/common/event';
import { IDisposable } from 'vs/base/common/lifecycle';
import { URI } from 'vs/base/common/uri';
import * as modes from 'vs/editor/common/modes';
import * as nls from 'vs/nls';
import { RawContextKey } from 'vs/platform/contextkey/common/contextkey';
import { ExtensionIdentifier } from 'vs/platform/extensions/common/extensions';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { IMouseWheelEvent } from 'vs/base/browser/mouseEvent';

/**
 * Set when the find widget in a webview is visible.
 */
export const KEYBINDING_CONTEXT_WEBVIEW_FIND_WIDGET_VISIBLE = new RawContextKey<boolean>('webviewFindWidgetVisible', false);
export const KEYBINDING_CONTEXT_WEBVIEW_FIND_WIDGET_FOCUSED = new RawContextKey<boolean>('webviewFindWidgetFocused', false);

export const webviewHasOwnEditFunctionsContextKey = 'webviewHasOwnEditFunctions';
export const webviewHasOwnEditFunctionsContext = new RawContextKey<boolean>(webviewHasOwnEditFunctionsContextKey, false);

export const IWebviewService = createDecorator<IWebviewService>('webviewService');

export interface WebviewIcons {
	readonly light: URI;
	readonly dark: URI;
}

/**
 * Handles the creation of webview elements.
 */
export interface IWebviewService {
	readonly _serviceBrand: undefined;

	createWebviewElement(
		id: string,
		options: WebviewOptions,
		contentOptions: WebviewContentOptions,
		extension: WebviewExtensionDescription | undefined,
	): WebviewElement;

	createWebviewOverlay(
		id: string,
		options: WebviewOptions,
		contentOptions: WebviewContentOptions,
		extension: WebviewExtensionDescription | undefined,
	): WebviewOverlay;

	setIcons(id: string, value: WebviewIcons | undefined): void;
}

export const enum WebviewContentPurpose {
	NotebookRenderer = 'notebookRenderer',
	CustomEditor = 'customEditor',
}

export interface WebviewOptions {
	// The purpose of the webview; this is (currently) only used for filtering in js-debug
	readonly purpose?: WebviewContentPurpose;
	readonly customClasses?: string;
	readonly enableFindWidget?: boolean;
	readonly tryRestoreScrollPosition?: boolean;
	readonly retainContextWhenHidden?: boolean;
}

export interface WebviewContentOptions {
	readonly allowMultipleAPIAcquire?: boolean;
	readonly allowScripts?: boolean;
	readonly localResourceRoots?: ReadonlyArray<URI>;
	readonly portMapping?: ReadonlyArray<modes.IWebviewPortMapping>;
	readonly enableCommandUris?: boolean;
}

export interface WebviewExtensionDescription {
	readonly location: URI;
	readonly id: ExtensionIdentifier;
}

export interface IDataLinkClickEvent {
	dataURL: string;
	downloadName?: string;
}

export interface Webview extends IDisposable {
	html: string;
	contentOptions: WebviewContentOptions;
	localResourcesRoot: URI[];
	extension: WebviewExtensionDescription | undefined;
	initialScrollProgress: number;
	state: string | undefined;

	readonly onDidFocus: Event<void>;
	readonly onDidBlur: Event<void>;
	readonly onDidClickLink: Event<string>;
	readonly onDidScroll: Event<{ scrollYPercentage: number }>;
	readonly onDidWheel: Event<IMouseWheelEvent>;
	readonly onDidUpdateState: Event<string | undefined>;
	readonly onDidReload: Event<void>;
	readonly onMessage: Event<any>;
	readonly onMissingCsp: Event<ExtensionIdentifier>;

	postMessage(data: any): void;

	focus(): void;
	reload(): void;

	showFind(): void;
	hideFind(): void;
	runFindAction(previous: boolean): void;

	selectAll(): void;
	copy(): void;
	paste(): void;
	cut(): void;
	undo(): void;
	redo(): void;

	windowDidDragStart(): void;
	windowDidDragEnd(): void;
}

/**
 * Basic webview rendered in the dom
 */
export interface WebviewElement extends Webview {
	mountTo(parent: HTMLElement): void;
}

/**
 * Dynamically created webview drawn over another element.
 */
export interface WebviewOverlay extends Webview {
	readonly container: HTMLElement;
	options: WebviewOptions;

	readonly onDispose: Event<void>;

	claim(owner: any): void;
	release(owner: any): void;

	getInnerWebview(): Webview | undefined;

	layoutWebviewOverElement(element: HTMLElement, dimension?: Dimension): void;
}

export const webviewDeveloperCategory = { value: nls.localize({ key: 'developer', comment: ['A developer on Code itself or someone diagnosing issues in Code'] }, "Developer"), original: 'Developer' };


text:
package org.sikuli.slides.api.actions;

import java.awt.Color;

import org.sikuli.api.ScreenRegion;
import org.sikuli.api.visual.Canvas;
import org.sikuli.api.visual.ScreenRegionCanvas;
import org.sikuli.slides.api.Context;

import com.google.common.base.Objects;

public class DisplayLabelAction implements Action {

	private String text = "";
	private int fontSize = 12;
	private int duration = 3000;
	private Color backgroundColor = Color.yellow;
	private Canvas canvas;

	@Override
	public void execute(Context context){
		ScreenRegion targetRegion = context.getScreenRegion();
		String textToDisplay = context.render(text);

		canvas = new ScreenRegionCanvas(targetRegion);
		canvas.add().label(textToDisplay).inside(targetRegion)
					.styleWith()
						.color(Color.black)
						.fontSize((int)fontSize)
						.lineWidth(2)
						.backgroundColor(backgroundColor);
		canvas.show();
	}

	@Override
	public void stop(){
		canvas.hide();
	}

	public String getText() {
		return text;
	}

	public void setText(String text) {
		this.text = text;
	}

	public int getFontSize() {
		return fontSize;
	}

	public void setFontSize(int fontSize) {
		this.fontSize = fontSize;
	}

	public int getDuration() {
		return duration;
	}

	public void setDuration(int duration) {
		this.duration = duration;
	}

	public Color getBackgroundColor() {
		return backgroundColor;
	}

	public void setBackgroundColor(Color backgroundColor) {
		this.backgroundColor = backgroundColor;
	}

	public String toString(){
		return Objects.toStringHelper(this).add("text", text).toString();
	}
}


text:
{{ page.title }}

					{% if page.support %}

Support: Opera {{ page.support }}+

					{% endif %}
					{% assign author = site.authors[page.author] %}
					{% if page.author %}

by {% if author.github %}{% endif %}{{ author.display_name }}{% if author.github %}{% endif %}

					{% endif %}


text:
package com.github.jjobes.slidedaytimepicker;

import java.text.SimpleDateFormat;
import java.util.Calendar;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;

/**
 *
The {@code DialogFragment} that contains the {@link SlidingTabLayout} and
 * {@link CustomViewPager}.

 *
 *
The {@code CustomViewPager} contains the {@link DayFragment} and {@link TimeFragment}.

 *
 *
This {@code DialogFragment} is managed by {@link SlideDayTimePicker}.

 *
 * @author jjobes
 *
 */
public class SlideDayTimeDialogFragment extends DialogFragment implements DayFragment.DayChangedListener,
                                                                          TimeFragment.TimeChangedListener
{
    public static final String TAG_SLIDE_DAY_TIME_DIALOG_FRAGMENT = "tagSlideDayTimeDialogFragment";

    private static SlideDayTimeListener mListener;

    private Context mContext;
    private CustomViewPager mViewPager;
    private ViewPagerAdapter mViewPagerAdapter;
    private SlidingTabLayout mSlidingTabLayout;
    private View mButtonHorizontalDivider;
    private View mButtonVerticalDivider;
    private Button mOkButton;
    private Button mCancelButton;
    private boolean mIsCustomDaysArraySpecified;
    private String[] mCustomDaysArray;
    private String[] mDaysArray;
    private int mDayIndex;
    private int mHour;
    private int mMinute;
    private int mTheme;
    private int mIndicatorColor;
    private boolean mIsClientSpecified24HourTime;
    private boolean mIs24HourTime;
    private Calendar mCalendar;

    public SlideDayTimeDialogFragment()
    {
        // Required empty public constructor
    }

    /**
     *
Return a new instance of {@code SlideDayTimeDialogFragment} with its bundle
     * filled with the incoming arguments.

     *
     *
Called by {@link SlideDayTimePicker#show()}.

     *
     * @param listener
     * @param isCustomDaysArraySpecified
     * @param initialDay
     * @param initialHour
     * @param initialMinute
     * @param isClientSpecified24HourTime
     * @param is24HourTime
     * @param theme
     * @param indicatorColor
     * @return
     */
    public static SlideDayTimeDialogFragment newInstance(SlideDayTimeListener listener,
            boolean isCustomDaysArraySpecified, String[] customDaysArray, int initialDay,
            int initialHour, int initialMinute, boolean isClientSpecified24HourTime,
            boolean is24HourTime, int theme, int indicatorColor)
    {
        // Set listener to a static member variable in order to avoid the
        // NotSerializableException on rotation.
        mListener = listener;

        // Create a new instance of SlideDayTimeDialogFragment
        SlideDayTimeDialogFragment dialogFragment = new SlideDayTimeDialogFragment();

        // Store the arguments and attach the bundle to the fragment
        Bundle bundle = new Bundle();
        bundle.putBoolean("isCustomDaysArraySpecified", isCustomDaysArraySpecified);
        bundle.putStringArray("customDaysArray", customDaysArray);
        bundle.putInt("initialDay", initialDay);
        bundle.putInt("initialHour", initialHour);
        bundle.putInt("initialMinute", initialMinute);
        bundle.putBoolean("isClientSpecified24HourTime", isClientSpecified24HourTime);
        bundle.putBoolean("is24HourTime", is24HourTime);
        bundle.putInt("theme", theme);
        bundle.putInt("indicatorColor", indicatorColor);
        dialogFragment.setArguments(bundle);

        // Return the fragment with its bundle
        return dialogFragment;
    }

    @Override
    public void onAttach(Activity activity)
    {
        super.onAttach(activity);

        mContext = activity;
    }

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        setRetainInstance(true);

        mDaysArray = getResources().getStringArray(R.array.days_array);

        unpackBundle();

        if (!mIsCustomDaysArraySpecified)
            mDayIndex--;

        mCalendar = Calendar.getInstance();
        mCalendar.set(Calendar.HOUR_OF_DAY, mHour);
        mCalendar.set(Calendar.MINUTE, mMinute);

        switch (mTheme)
        {
        case SlideDayTimePicker.HOLO_DARK:
            setStyle(DialogFragment.STYLE_NO_TITLE, android.R.style.Theme_Holo_Dialog_NoActionBar);
            break;
        case SlideDayTimePicker.HOLO_LIGHT:
            setStyle(DialogFragment.STYLE_NO_TITLE, android.R.style.Theme_Holo_Light_Dialog_NoActionBar);
            break;
        default:  // if no theme was specified, default to holo light
            setStyle(DialogFragment.STYLE_NO_TITLE, android.R.style.Theme_Holo_Light_Dialog_NoActionBar);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        View view = inflater.inflate(R.layout.slide_day_time_picker, container);

        setupViews(view);
        customizeViews();
        initViewPager();
        initTabs();
        initButtons();

        return view;
    }

    @Override
    public void onDestroyView()
    {
        // Workaround for a bug in the compatibility library where calling
        // setRetainInstance(true) does not retain the instance across
        // orientation changes.
        if (getDialog() != null && getRetainInstance())
        {
            getDialog().setDismissMessage(null);
        }

        super.onDestroyView();
    }

    private void unpackBundle()
    {
        Bundle args = getArguments();

        mIsCustomDaysArraySpecified = args.getBoolean("isCustomDaysArraySpecified");
        mCustomDaysArray = args.getStringArray("customDaysArray");
        mDayIndex = args.getInt("initialDay");
        mHour = args.getInt("initialHour");
        mMinute = args.getInt("initialMinute");
        mIsClientSpecified24HourTime = args.getBoolean("isClientSpecified24HourTime");
        mIs24HourTime = args.getBoolean("is24HourTime");
        mTheme = args.getInt("theme");
        mIndicatorColor = args.getInt("indicatorColor");
    }

    private void setupViews(View v)
    {
        mViewPager = (CustomViewPager) v.findViewById(R.id.viewPager);
        mSlidingTabLayout = (SlidingTabLayout) v.findViewById(R.id.slidingTabLayout);
        mButtonHorizontalDivider = v.findViewById(R.id.buttonHorizontalDivider);
        mButtonVerticalDivider = v.findViewById(R.id.buttonVerticalDivider);
        mOkButton = (Button) v.findViewById(R.id.okButton);
        mCancelButton = (Button) v.findViewById(R.id.cancelButton);
    }

    private void customizeViews()
    {
        int lineColor = mTheme == SlideDayTimePicker.HOLO_DARK ?
                getResources().getColor(R.color.gray_holo_dark) :
                    getResources().getColor(R.color.gray_holo_light);

        // Set the colors of the horizontal and vertical lines for the
        // bottom buttons depending on the theme.
        switch (mTheme)
        {
        case SlideDayTimePicker.HOLO_LIGHT:
        case SlideDayTimePicker.HOLO_DARK:
            mButtonHorizontalDivider.setBackgroundColor(lineColor);
            mButtonVerticalDivider.setBackgroundColor(lineColor);
            break;

        default:  // if no theme was specified, default to holo light
            mButtonHorizontalDivider.setBackgroundColor(getResources().getColor(R.color.gray_holo_light));
            mButtonVerticalDivider.setBackgroundColor(getResources().getColor(R.color.gray_holo_light));
        }

        // Set the color of the selected tab underline if one was specified.
        if (mIndicatorColor != 0)
            mSlidingTabLayout.setSelectedIndicatorColors(mIndicatorColor);
    }

    private void initViewPager()
    {
        mViewPagerAdapter = new ViewPagerAdapter(getChildFragmentManager());
        mViewPager.setAdapter(mViewPagerAdapter);

        // Setting this custom layout for each tab ensures that the tabs will
        // fill all available horizontal space.
        mSlidingTabLayout.setCustomTabView(R.layout.custom_tab, R.id.tabText);
        mSlidingTabLayout.setViewPager(mViewPager);
    }

    private void initTabs()
    {
        // Set intial date on date tab
        updateDayTab();

        // Set initial time on time tab
        updateTimeTab();
    }

    private void initButtons()
    {
        mOkButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v)
            {
                if (mListener == null)
                {
                    throw new NullPointerException(
                            "Listener no longer exists for mOkButton");
                }

                // mDayIndex currenly holds the index of the day in days_array,
                // but we want to return a day integer that is compliant with
                // the java.util.Calendar API, so we increment it by 1 if they're
                // using the built-in days array.  If the user specifies their
                // own custom array, return the raw index.
                int returnDay;

                if (!mIsCustomDaysArraySpecified)
                {
                    returnDay = mDayIndex + 1;
                }
                else
                {
                    returnDay = mDayIndex;
                }

                mListener.onDayTimeSet(returnDay, mHour, mMinute);

                dismiss();
            }
        });

        mCancelButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v)
            {
                if (mListener == null)
                {
                    throw new NullPointerException(
                            "Listener no longer exists for mCancelButton");
                }

                mListener.onDayTimeCancel();

                dismiss();
            }
        });
    }

    /**
     *
The callback used by the day picker to update {@code mCalendar} as
     * the user changes the date. Each time this is called, we update the
     * day tab to reflect the day the user has currenly selected.

     *
     *
Implements the {@link DayFragment.DayChangedListener} interface.

     */
    @Override
    public void onDayChanged(int day)
    {
        mDayIndex = day;  // Sunday 0, Monday 1, ... Saturday 6

        updateDayTab();
    }

    /**
     *
The callback used by the time picker to update {@code mCalendar}
     * as the user changes the time. Each time this is called, we update
     * the time tab to reflect the time the user has currenly selected.

     *
     *
Implements the {@link TimeFragment.TimeChangedListener} interface.

     */
    @Override
    public void onTimeChanged(int hour, int minute)
    {
        mHour = hour;
        mMinute = minute;

        mCalendar.set(Calendar.HOUR_OF_DAY, mHour);
        mCalendar.set(Calendar.MINUTE, mMinute);

        updateTimeTab();
    }

    private void updateDayTab()
    {
        if (mIsCustomDaysArraySpecified)
            mSlidingTabLayout.setTabText(0, mCustomDaysArray[mDayIndex]);
        else
            mSlidingTabLayout.setTabText(0, mDaysArray[mDayIndex]);
    }

    @SuppressLint("SimpleDateFormat")
    private void updateTimeTab()
    {
        if (mIsClientSpecified24HourTime)
        {
            SimpleDateFormat formatter;

            if (mIs24HourTime)
            {
                formatter = new SimpleDateFormat("HH:mm");
                mSlidingTabLayout.setTabText(1, formatter.format(mCalendar.getTime()));
            }
            else
            {
                formatter = new SimpleDateFormat("h:mm aa");
                mSlidingTabLayout.setTabText(1, formatter.format(mCalendar.getTime()));
            }
        }
        else  // display time using the device's default 12/24 hour format preference
        {
            mSlidingTabLayout.setTabText(1, DateFormat.getTimeFormat(
                    mContext).format(mCalendar.getTimeInMillis()));
        }
    }

    /**
     *
Called when the user clicks outside the dialog or presses the device's
     * Back button.

     *
     *
Note: Actual Cancel button clicks are handled by {@code mCancelButton}'s
     * event handler.

     */
    @Override
    public void onCancel(DialogInterface dialog)
    {
        super.onCancel(dialog);

        if (mListener == null)
        {
            throw new NullPointerException(
                    "Listener no longer exists in onCancel()");
        }

        mListener.onDayTimeCancel();
    }

    private class ViewPagerAdapter extends FragmentPagerAdapter
    {
        public ViewPagerAdapter(FragmentManager fm)
        {
            super(fm);
        }

        @Override
        public Fragment getItem(int position)
        {
            switch (position)
            {
            case 0:
                Fragment dayFragment = DayFragment.newInstance(
                        mTheme,
                        mDayIndex,
                        mIsCustomDaysArraySpecified,
                        mCustomDaysArray);
                dayFragment.setTargetFragment(SlideDayTimeDialogFragment.this, 100);
                return dayFragment;
            case 1:
                Fragment timeFragment = TimeFragment.newInstance(
                        mTheme,
                        mCalendar.get(Calendar.HOUR_OF_DAY),
                        mCalendar.get(Calendar.MINUTE),
                        mIsClientSpecified24HourTime,
                        mIs24HourTime);
                timeFragment.setTargetFragment(SlideDayTimeDialogFragment.this, 200);
                return timeFragment;
            }

            return null;
        }

        @Override
        public int getCount()
        {
            return 2;
        }
    }
}


text:
package com.esri.arcgis.android.samples.featuredusergroup;

import android.app.Activity;
import android.app.FragmentManager;
import android.os.Bundle;

/**
 * The primary purpose of this sample is to show how to log in to a portal, fetch info about the
 * featured groups, fetch info about webmap items in a particular group, then fetch and display a
 * particular webmap.
 *

 * A secondary purpose is to demonstrate two different techniques for handling device configuration
 * changes.
 *

 * This is the main activity of this sample. It simply hosts the GroupsFragment and the
 * ItemsFragment. On startup it launches a GroupsFragment.
 */
public class FeaturedGroupsActivity extends Activity {

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Set content view and setup action bar
    setContentView(R.layout.featured_groups_activity);
    getActionBar().setDisplayHomeAsUpEnabled(false);
    getActionBar().setHomeButtonEnabled(false);

    // Only if this is a fresh start, kick off the GroupsFragment
    if (savedInstanceState == null) {
      FragmentManager fragMgr = getFragmentManager();
      fragMgr.beginTransaction().add(R.id.main_fragment_container, new GroupsFragment(), null)
          .commit();
    }
  }

}


text:
layout: post
title:  "Cutaway Dimple"
date:   2016-03-26 21:59:07
categories: lock
tags: dimple
image: /images/lock-5.png
picked: true
number: 4
---

# {{page.number}} {{ page.title }}

{% if page.picked %}
### Status: <i class="fa fa-unlock"/>
{% else %}
### Status: <i class="fa fa-lock"/>
{% endif %}

### Description

Cutaway Dimple Lock from Amazon.

### Methods

- SPP'd while looking

### Notes

- Dimples are tricky, none of the tools properly fits.
- Getting the last pin down far enough is the tricky bit.


text:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="live.flume.wireless.debugger">

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

    <application android:allowBackup="true"
                 android:label="@string/app_name"
                 android:supportsRtl="true">

        <service android:name="live.flume.wireless.debugger.WirelessDebugger"
                 android:process=":WirelessDebugger"/>

    </application>

</manifest>


text:
exports.config = {
    // See http://brunch.io/#documentation for docs.
    files: {
        javascripts: {
            joinTo: "js/app.js",
            order: {
                before: [
                    'vendor/jquery.min.js',
                    'vendor/jquery.dataTables.min.js',
                    'vendor/bootstrap.min.js',
                    'vendor/patternfly.min.js',
                ]
            }
        },
        stylesheets: {
            joinTo: "css/app.css",
            order: {
                before: 'vendor/patternfly.min.css'
            }
        },
        templates: {
            joinTo: "js/app.js"
        }
    },

    conventions: {
        // This option sets where we should place non-css and non-js assets in.
        // By default, we set this to "/assets/static". Files in this directory
        // will be copied to `paths.public`, which is "priv/static" by default.
        assets: /^(static)/
    },

    // Phoenix paths configuration
    paths: {
        // Dependencies and current project directories to watch
        watched: ["static", "css", "js", "vendor"],
        // Where to compile files to
        public: "../priv/static"
    },

    // Configure your plugins
    plugins: {
        babel: {
            // Do not use ES6 compiler in vendor code
            ignore: [/vendor/]
        }
    },

    modules: {
        autoRequire: {
            "js/app.js": ["js/app"]
        }
    },

    npm: {
        enabled: true,
        globals: {
            $: 'jquery',
            jQuery: 'jquery'
        }
    }
};


text:
@interface T8DataBaseModel : NSObject<NSCoding>

- (id)initWithDict:(NSDictionary *)dict;

- (void)save;
- (void)saveSynchronous:(BOOL)sync;
- (void)deleteObject;
- (void)deleteObjectSynchronous:(BOOL)sync;
+ (NSMutableArray *)queryWithCondition:(NSString *)condition;
+ (void)saveBatchItems:(NSArray *)items;
+ (void)saveBatchItems:(NSArray *)items synchronous:(BOOL)sync;
+ (void)clearTableSynchronous:(BOOL)sync;
+ (void)deleteWithCondition:(NSString *)condition synchronous:(BOOL)sync;

+ (NSString *)tableName;
+ (NSString *)primaryKey;
+ (NSArray *)ignoreProperties;
+ (NSArray *)saveIgnoreProperties;

- (NSString *)jsUnescape:(NSString *)str;

@end


text:
module.exports = {
  up: (queryInterface, Sequelize) =>
    queryInterface.addColumn('courseUnit', 'weight', Sequelize.FLOAT),

  down: queryInterface => queryInterface.removeColumn('courseUnit', 'weight'),
};


text:
#pragma once

#include "Enums.h"

namespace SlimDX
{
	namespace Direct3D9
	{
		/// <summary>Defines the attributes of a font.</summary>
		/// <unmanaged>D3DXFONT_DESC</unmanaged>
		public value class FontDescription : System::IEquatable<FontDescription>
		{
		public:
			property int Height;
            property int Width;
            property FontWeight Weight;
            property int MipLevels;
            property bool Italic;
            property CharacterSet CharSet;
            property Precision OutputPrecision;
            property FontQuality Quality;
            property PitchAndFamily PitchAndFamily;
            property System::String^ FaceName;

			static bool operator == ( FontDescription left, FontDescription right );
			static bool operator != ( FontDescription left, FontDescription right );

			virtual int GetHashCode() override;
			virtual bool Equals( System::Object^ obj ) override;
			virtual bool Equals( FontDescription other );
			static bool Equals( FontDescription% value1, FontDescription% value2 );
		};
	}
}


text:
package java.net;

import javax.net.ssl.HttpsURLConnection;
import java.util.Hashtable;

public final class URL implements java.io.Serializable {

    private String protocol;
    private String host;
    private int port;
    private String file;

    public URL(String protocol, String host, int port, String file) throws MalformedURLException {
        this(protocol, host, port, file, null);
    }

    public URL(String protocol, String host, String file) throws MalformedURLException {
        this(protocol, host, -1, file);
    }

    public URL(String protocol, String host, int port, String file,
               URLStreamHandler handler) throws MalformedURLException {
        this.protocol = protocol;
        this.host = host;
        this.file = file;
        this.port = port;
    }

    public URL(String spec) throws MalformedURLException {
        this(null, spec);
    }

    public URL(URL context, String spec) throws MalformedURLException {
        this(context, spec, null);
    }

    public URL(URL context, String spec, URLStreamHandler handler) throws MalformedURLException {
        protocol = spec;
    }

    public URLConnection openConnection(Proxy proxy) throws java.io.IOException {
        if (protocol == "jar") {
            return new JarURLConnection(this);
        } else if (protocol == "http") {
            return new HttpURLConnection(this);
        } else if (protocol == "https") {
            return new HttpsURLConnection(this);
        } else
            return new URLConnection(this);
    }

    public URLConnection openConnection() throws java.io.IOException {
        return openConnection(null);
    }

}


text:
"Save the Haggis"
=====================================

Authors: Migael Strydom
         Timothy Stranex

This game was completed by the authors as a project for the CSC2002S course
at the University of Cape Town in 2006. We are now releasing it under the
Apache 2.0 license.

Overview
--------
"Save the Haggis" is a turn-based computer game in 3D where the
player sets off on a quest to destroy a mythical creature called a Haggis. The
game is called "Save the Haggis" as opposed to "Destroy the Haggis"
because of an ironic plot development in the game. According to the in-game
story in the introduction of the game, a country that had been eating Haggis
for generations had finally agreed to honoring the rights of the Haggis not
to be eaten, and were in the process of a political move to outlaw the eating
of Haggis. The aim of the hero in this game is to undermine this whole "Save
the Haggis" campaign.

Gameplay
--------
The gameplay takes place in a maze. The game is turn-based, alternating
between the hero's turn and the Haggis' turn. During the hero's turn, the user
can choose to move the hero to an adjacent cell in the maze (that is, take a
single step), jump over several intermediate cells to get to a cell that is not
adjacent, throw a grenade, use a psychic ability, or do nothing for the
turn. Each of these moves can be useful in overcoming obstacles in the maze,
discovering obstacles in the maze, or cunning tactics to defeat the
Haggis. During the Haggis' turn, it also has the option of any of the actions
the hero can do, and the program will decide what it is that the Haggis does
to avoid being defeated.

The hero has certain attributes. These attributes include health, energy and
ammunition. When the hero runs out of health or energy, the haggis wins the
game. The amount of ammunition is the number of grenades the hero can
throw. Every time the hero takes a step, he loses a bit of energy, but not as
much as when the hero jumps to a new cell. Health is lost when the hero gets
injured by the Haggis, which is when the Haggis throws a grenade at the hero,
or when the hero steps on a cell that contains a trap. The Haggis also has
these attributes and the same rules apply to it.

The maze consists of cells, some containing items and some containing a
wall. The hero and the Haggis each need to be occupying exactly one of the
cells at any one time, with the only conditions being that neither the hero
nor the Haggis can occupy a cell containing a wall, and they cannot occupy the
same cell. Some cells also contain items. When the hero steps on a cell that
contains an item, the effect of that item gets played out on the hero. Items
basically only alter the attributes of the hero in some way. There are health
items to increase the hero's health, and traps that decrease it. There are
also energy items to increase the hero's energy and ammunition crates that
increase the number of grenades the hero is carrying. The Haggis can also pick
up items on a cell.

The object of the game, with all these rules in place, is to attempt to kill
the Haggis by making either its health or its energy drop to zero, while not
being killed by the Haggis or traps in the maze first. Once this goal has been
achieved, the game will be over.

System Requirements
-------------------

  - Linux/FreeBSD
  - An OpenGL capable graphics card
  - SDL
  - Pentium 4 or equivalent or higher
  - 256MB RAM

Quick Start
-----------

cd build
./haggis
(runs the game)
./haggis --test
(runs the unit tests)
cd doc
ls
(the documentation in .pdf format)

Dependencies:
  - OpenGL
  - libSDL
  - SDL_image
  - CppUnit

Building
--------

You can build the whole project by typing "make". This will build both the
documentation and the program and put them in the build directory. To build the
documentation, you need
   - LaTeX;
   - epstopdf; and,
   - python.
To build the program, you need
   - libSDL;
   - SDL_image;
   - OpenGL; and,
   - CppUnit.
You may need to edit src/Makefile and src/test/Makefile to add include and
library paths for CppUnit. You can build just the source by typing "make"
in the src/ directory. (In that case, the build output is in the src/
directory instead of the build/ directory.)

Files
-----

build/          Build output directory
build/haggis    The game binary
build/doc/      Documentation in .pdf format
build/images/   Images needed by the game
build/test/     Test data needed by the unit tests

src/            The source code and data
src/game/       Source code for the game
src/test/       Unit testing code and data
src/images/     Images needed for the game
src/level1.hag  The level file


text:
package daos

import models.Shrt
import org.junit.runner._
import org.specs2.mutable._
import org.specs2.runner._
import play.api.test._
import scala.collection.LinearSeq
import scaldi._
import utils.test.WithFakeDb

@RunWith(classOf[JUnitRunner])
class ShrtDaoSpec extends Specification {
  private val dao = new ShrtDaoH2Impl()

  "The ShrtDao" should {
    "read a Shrt from its url" in new WithFakeDb(scripts = LinearSeq("test/resources/sql/shrtdaospec.1.sql")) {
      dao.read(new java.net.URL("http://www.google.com")) ===
      Some(Shrt("Google", new java.net.URL("http://www.google.com"), "googl", Some("This is Google"), Set("foo", "bar"), 12))
    }
    "read a Shrt from its url and return None iff not found" in new WithFakeDb(scripts = LinearSeq("test/resources/sql/shrtdaospec.1.sql")) {
      dao.read(new java.net.URL("http://www.absent.com")) === None
    }
    "read a Shrt from its token" in new WithFakeDb(scripts = LinearSeq("test/resources/sql/shrtdaospec.1.sql")) {
      dao.read("googl") === Some(Shrt("Google", new java.net.URL("http://www.google.com"), "googl", Some("This is Google"), Set("foo", "bar"), 12))
    }
    "read a Shrt form its token and return None iff not found" in new WithFakeDb(scripts = LinearSeq("test/resources/sql/shrtdaospec.1.sql")) {
      dao.read("absent") === None
    }
    "read all Shrt(s)" in new WithFakeDb(scripts = LinearSeq("test/resources/sql/shrtdaospec.1.sql")) {
      val actual = dao.all()
      actual.size must equalTo (3)
    }
    "save a Shrt" in new WithFakeDb(scripts = LinearSeq("test/resources/sql/shrtdaospec.1.sql")) {
      val expected = Shrt("Hacker News", new java.net.URL("http://www.hackernews.scom"), "hwught", Some("This is bullshits!"), Set("startup", "money"), 13)
      val id = dao.save(expected)
      id === Some(5)
      dao.read("hwught") === Some(expected)
    }
    "inc the `count` field in a pre-existing Shrt" in new WithFakeDb(scripts = LinearSeq("test/resources/sql/shrtdaospec.1.sql")) {
      dao.inc("fcbk") === Some(10)
      dao.read("fcbk") === Some(Shrt("Facebook", new java.net.URL("http://www.facebook.com"), "fcbk", Some("This is Facebook"), count = 10))
    }
    "return None after trying to inc the `count` field of a non existent Shrt" in new WithFakeDb(scripts = LinearSeq("test/resources/sql/shrtdaospec.1.sql")) {
      dao.inc("absent") === None
    }
    "delete a Shrt" in new WithFakeDb(scripts = LinearSeq("test/resources/sql/shrtdaospec.1.sql")) {
      dao.delete("fcbk") === Some(Shrt("Facebook", new java.net.URL("http://www.facebook.com"), "fcbk", Some("This is Facebook"), count = 9))
      dao.read("fcbk") === None
    }
    "return a None after trying to delete a non existent Shrt" in new WithFakeDb(scripts = LinearSeq("test/resources/sql/shrtdaospec.1.sql")) {
      dao.delete("absent") === None
    }
    "return the top most accessed K Shrts if any" in new WithFakeDb(scripts = LinearSeq("test/resources/sql/shrtdaospec.1.sql")) {
      dao.topK(3).map { _.count } === List(12, 10, 9)
      dao.topK(2).map { _.count } === List(12, 10)
      dao.topK(1).map { _.count } === List(12)
      dao.topK(0) === List.empty[Shrt]
      dao.topK(-1) === List.empty[Shrt]
    }
    "return the max possible number of Shrts if there are less than K available" in new WithFakeDb(scripts = LinearSeq("test/resources/sql/shrtdaospec.1.sql")) {
      dao.topK(30).map { _.count } === List(12, 10, 9)
    }
    "return an empty linear seq of Shrts if there are no available" in new WithFakeDb(scripts = Nil) {
      dao.topK(2) === List.empty[Shrt]
    }
  }
}


text:
void registerErrorLogCallback(errorLogCallback callback) {
    sqlite3_config(SQLITE_CONFIG_LOG, callback, 0);
}


text:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * Created by JetBrains PhpStorm.
 * User: jason
 * Date: 5/25/11
 * Time: 11:22 AM
 * To change this template use File | Settings | File Templates.
 */

class Script extends CI_Controller {

    public function maya_redo()
    {

        $this->load->view('mayaredo');
    }

    public function maya_post()
    {
        $config = array(
            'upload_path'   => './uploads',
            'allowed_types' => 'csv'
        );
        $this->load->library('upload', $config);

        $this->upload->do_upload();

        $errors = $this->upload->display_errors();

        if ($errors) {

            $this->session->set_userdata('error', $errors);
            redirect('errors/error_page');
        }

        $upload_data = $this->upload->data();

        $this->load->model('Script_Model');

        $csvName = $upload_data['file_name'];

        $origVendor = (string)$this->input->post('oldvendor', TRUE);
        $newVendor = (string)$this->input->post('newvendor', TRUE);

        $this->Script_Model->changeVendor($csvName, $origVendor, $newVendor);

    }

    public function lead_post()
    {
        $config = array(
            'upload_path'   => './uploads',
            'allowed_types' => 'csv'
        );
        $this->load->library('upload', $config);

        $this->upload->do_upload();

        $errors = $this->upload->display_errors();

        if ($errors) {

            $this->session->set_userdata('error', $errors);
            redirect('errors/error_page');
        }

        $upload_data = $this->upload->data();

        $this->load->model('Script_Model');

        $csvName = $upload_data['file_name'];

        $this->Script_Model->uploadLeads($csvName);

    }

    function success($ucount, $bcount)
    {
        $data['updated'] = $this->session->userdata('updated');
        $data['unupdated'] = $this->session->userdata('unupdated');
        $this->load->view('successPage', $data);
    }

}


text:
/* global VERSION */
import DevtoolsBase from './base'
import WebSocket from 'universal-websocket-client'

export class Devtools extends DevtoolsBase {
  constructor(options) {
    super(options)
    this.trees = []
    this.latestExecutionId = null
    this.version = VERSION
    this.init()
  }
  createSocket() {
    this.ws = new WebSocket(`ws://${this.host}`)
  }
  onMessage(event) {
    const message = JSON.parse(event.data)
    switch (message.type) {
      case 'pong':
        this.sendInitial()
        break
      case 'ping':
        this.sendInitial()
        break
    }
  }
  add(tree) {
    this.trees.push(tree)
    tree.contextProviders.unshift(this.Provider())
    this.watchExecution(tree, 'ft')
  }
  remove(tree) {
    this.trees.splice(this.trees.indexOf(tree), 1)
    tree.contextProviders.splice(0, 1)

    tree.removeAllListeners('start')
    tree.removeAllListeners('end')
    tree.removeAllListeners('pathStart')
    tree.removeAllListeners('functionStart')
    tree.removeAllListeners('functionEnd')
    tree.removeAllListeners('error')
  }
  removeAll() {
    const trees = this.trees.reduce((newTrees, tree) => {
      newTrees.push(tree)
      return newTrees
    }, [])
    trees.forEach(tree => {
      this.remove(tree)
    })
  }
  sendInitial() {
    const message = JSON.stringify({
      type: 'init',
      source: 'ft',
      version: this.version,
    })

    this.sendMessage(message)
    if (this.backlog.length) {
      this.sendBulkMessage(this.backlog, 'ft')
      this.backlog = []
    }
    this.isConnected = true
  }
  /*
    Create the stringified message for the debugger. As we need to
    store mutations with the default true "storeMutations" option used
    by time travel and jumping between Cerebral apps, we are careful
    not doing unnecessary stringifying.
  */
  createExecutionMessage(debuggingData, context, functionDetails, payload) {
    const type = 'execution'
    const data = {
      execution: {
        executionId: context.execution.id,
        functionIndex: functionDetails.functionIndex,
        payload: payload,
        datetime: context.execution.datetime,
        data: debuggingData,
      },
    }

    return this.safeStringify({
      type: type,
      source: 'ft',
      version: this.version,
      data: data,
    })
  }
  Provider() {
    const sendExecutionData = this.sendExecutionData.bind(this)
    function provider(context, functionDetails, payload) {
      context.debugger = {
        send(data) {
          sendExecutionData(data, context, functionDetails, payload)
        },
        wrapProvider(providerKey) {
          const provider = context[providerKey]

          context[providerKey] = Object.keys(
            provider
          ).reduce((wrappedProvider, key) => {
            const originalFunc = provider[key]

            wrappedProvider[key] = (...args) => {
              context.debugger.send({
                method: `${providerKey}.${key}`,
                args: args,
              })

              return originalFunc.apply(provider, args)
            }

            return wrappedProvider
          }, {})
        },
      }

      return context
    }

    return provider
  }
}

export default Devtools


text:
Working...

```
    if (maximumDate) {
        picker.maximumDate = maximumDate;
    }

    [picker showActionSheetPicker];

    if (picker.pickerView) {
        UIDatePicker *datePicker = (UIDatePicker *)picker.pickerView;
        NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"FR"];
        [datePicker setLocale:locale];
        [datePicker addTarget:self action:@selector(eventForDatePicker:) forControlEvents:UIControlEventValueChanged];
    }
```


text:
import { moduleForComponent, test } from 'ember-qunit';
//import hbs from 'htmlbars-inline-precompile';

moduleForComponent('search-result', 'Integration | Component | search result', {
    integration: true
});

test('it renders', function(assert) {
    // Set any properties with this.set('myProperty', 'value');
    // Handle any actions with this.on('myAction', function(val) { ... });

  // Have to skip this test due to 'undefined' MathJax breaking it (it is loaded on index.html)
  // this.render(hbs`{{search-result}}`);
  //
  // assert.equal(this.$().text().trim(), '');
  assert.ok('ok');
});


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
in Peck, Ann. Rep. N. Y. St. Mus. nat. Hist. 26: 77 (1874)

#### Original name
Uromyces sparganii subsp. sparganii

### Remarks
null


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.example.b00047562.parkinson_mhealth.Spiral"
    tools:showIn="@layout/activity_spiral">

    <TableLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:text="Spiral Drawing Area"
                android:id="@+id/textView3"
                android:layout_gravity="center" />
        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <Button
                android:layout_width="0dp"
                android:layout_height="50dp"
                android:text="@string/ClearSpiralDrawing"
                android:id="@+id/btn_clear"
                android:layout_gravity="center_horizontal"
                android:layout_weight="1" />

            <Button
                android:layout_width="0dp"
                android:layout_height="50dp"
                android:text="@string/btn_clear"
                android:id="@+id/btn_redraw"
                android:layout_gravity="center_horizontal"
                android:enabled="false"
                android:layout_weight="1" />

            <Button
                android:layout_width="wrap_content"
                android:layout_height="50dp"
                android:text="@string/SpiralSubmit"
                android:id="@+id/btnSubmit"
                android:enabled="false"
                android:layout_column="12" />
        </TableRow>

        <TableRow
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">

            <com.example.b00047562.parkinson_mhealth.CanvasSpiral
                android:id="@+id/spiral_canvas"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:textColor="#FFFFFF"
                android:layout_weight="1" />

        </TableRow>
    </TableLayout>

    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/fragment_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".ui.main.MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/header_background"
        android:orientation="vertical">

        <View
            android:layout_width="match_parent"
            android:layout_height="16dp" />

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <TextView
                android:layout_width="match_parent"
                android:layout_height="80dp"
                android:gravity="center_vertical"
                android:paddingLeft="24dp"
                android:text="@string/app_name"
                android:textColor="@color/header_text"
                android:textSize="32dp" />

            <CheckBox
                android:id="@+id/button_delay"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="right|bottom"
                android:layout_marginBottom="8dp"
                android:layout_marginRight="16dp"
                android:text="Delay" />

        </FrameLayout>

    </LinearLayout>

    <FrameLayout
        android:id="@+id/fragmentContainer"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>