text:
package org.apache.falcon.rerun.handler;

import org.apache.falcon.FalconException;
import org.apache.falcon.entity.ClusterHelper;
import org.apache.falcon.entity.store.ConfigurationStore;
import org.apache.falcon.entity.v0.Entity;
import org.apache.falcon.entity.v0.EntityType;
import org.apache.falcon.entity.v0.cluster.Cluster;
import org.apache.falcon.entity.v0.cluster.Interfacetype;
import org.apache.falcon.entity.v0.feed.Feed;
import org.apache.falcon.entity.v0.process.Process;
import org.apache.falcon.util.StartupProperties;
import org.apache.hadoop.conf.Configuration;
import org.mockito.MockitoAnnotations;
import org.testng.annotations.BeforeClass;

import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.StringWriter;
import java.util.Collection;

/**
 * Test class for Late data handling.
 */
public class TestLateData {

    protected static final String FEED_XML = "/feed-template.xml";
    protected static final String CLUSTER_XML = "/cluster-template.xml";
    protected static final String PROCESS_XML = "/process-template.xml";
    protected static final String PROCESS_XML2 = "/process-template2.xml";

    protected Configuration conf = new Configuration();

    @BeforeClass
    public void initConfigStore() throws Exception {
        MockitoAnnotations.initMocks(this);
        cleanupStore();
        String listeners = StartupProperties.get().getProperty("configstore.listeners");
        StartupProperties.get().setProperty("configstore.listeners",
                listeners.replace("org.apache.falcon.service.SharedLibraryHostingService", ""));
        ConfigurationStore.get().init();

    }

    protected void cleanupStore() throws FalconException {
        ConfigurationStore store = ConfigurationStore.get();
        for (EntityType type : EntityType.values()) {
            Collection<String> entities = store.getEntities(type);
            for (String entity : entities) {
                store.remove(type, entity);
            }
        }
    }

    protected void storeEntity(EntityType type, String name) throws Exception {
        Unmarshaller unmarshaller = type.getUnmarshaller();
        ConfigurationStore store = ConfigurationStore.get();
        store.remove(type, name);
        switch (type) {
        case CLUSTER:
            Cluster cluster = (Cluster) unmarshaller.unmarshal(this.getClass().getResource(CLUSTER_XML));
            cluster.setName(name);
            ClusterHelper.getInterface(cluster, Interfacetype.WRITE).setEndpoint(conf.get("fs.default.name"));
            store.publish(type, cluster);
            break;

        case FEED:
            Feed feed = (Feed) unmarshaller.unmarshal(this.getClass().getResource(FEED_XML));
            feed.setName(name);
            store.publish(type, feed);
            break;

        case PROCESS:
            Process process = (Process) unmarshaller.unmarshal(this.getClass().getResource(PROCESS_XML));
            process.setName(name);
            store.publish(type, process);
            break;

        default:
            throw new IllegalArgumentException("Invalid entity type: " + type);
        }
    }

    public void setup() throws Exception {
        ConfigurationStore store = ConfigurationStore.get();
        for (EntityType type : EntityType.values()) {
            for (String name : store.getEntities(type)) {
                store.remove(type, name);
            }
        }
        storeEntity(EntityType.CLUSTER, "testCluster");
        storeEntity(EntityType.PROCESS, "sample");
        storeEntity(EntityType.FEED, "raw-logs");
        storeEntity(EntityType.FEED, "clicks");
        Unmarshaller unmarshaller = EntityType.PROCESS.getUnmarshaller();
        Process process = (Process) unmarshaller.unmarshal(this.getClass().getResource(PROCESS_XML2));
        process.setName("sample2");
        store.publish(EntityType.PROCESS, process);
    }

    public String marshallEntity(final Entity entity) throws FalconException, JAXBException {
        Marshaller marshaller = entity.getEntityType().getMarshaller();
        StringWriter stringWriter = new StringWriter();
        marshaller.marshal(entity, stringWriter);
        return stringWriter.toString();
    }

/*
    @Test
    private void TestLateWhenInstanceRunning() throws Exception {
        try {
            WorkflowEngine engine = Mockito.mock(WorkflowEngine.class);
            when(engine.instanceStatus("testCluster", "123")).thenReturn("RUNNING");

            ConfigurationStore store = ConfigurationStore.get();
            setup();
            String nominalTime = EntityUtil.formatDateUTC(new Date(System.currentTimeMillis() - 1800000));
            InMemoryQueue<LaterunEvent> queue = new InMemoryQueue<LaterunEvent>(new File("target/late"));
            latedataHandler.init(queue);

            AbstractRerunHandler handle = RerunHandlerFactory.getRerunHandler(RerunEvent.RerunType.LATE);
            handle.handleRerun("sample", nominalTime, "123", "123", engine, System.currentTimeMillis());

            File directory = new File("target/late");
            File[] files = directory.listFiles();
            int noFilesBefore = files.length;

            Thread.sleep(90000);

            files = directory.listFiles();
            int noFilesAfterRetry = files.length;
            Assert.assertNotSame(noFilesBefore, noFilesAfterRetry);
        } catch (Exception e) {
            Assert.fail("Not expecting any exception");
        }
    }

    @Test
    private void TestLateWhenDataPresent() throws Exception {
        WorkflowEngine engine = Mockito.mock(WorkflowEngine.class);
        when(engine.instanceStatus("testCluster", "123")).thenReturn(
                "SUCCEEDED");

        LateRerunConsumer consumer = Mockito.mock(LateRerunConsumer.class);
        when(consumer.detectLate(Mockito.any(LaterunEvent.class))).thenReturn(
                "new data found");

        String nominalTime = EntityUtil.formatDateUTC(new Date(System
                .currentTimeMillis() - 1800000));
        AbstractRerunHandler handle = RerunHandlerFactory
                .getRerunHandler(RerunEvent.RerunType.LATE);

        ConfigurationStore store = ConfigurationStore.get();
        setup();

        InMemoryQueue<LaterunEvent> queue = new InMemoryQueue<LaterunEvent>(
                new File("target/late"));
        latedataHandler.init(queue);

        handle.handleRerun("sample", nominalTime, "123", "123", engine,
                System.currentTimeMillis());

        File directory = new File("target/late");
        File[] files = directory.listFiles();
        int noFilesBefore = files.length;

        Thread.sleep(90000);

        files = directory.listFiles();
        int noFilesAfterRetry = files.length;
        Assert.assertNotSame(noFilesBefore, noFilesAfterRetry);

    }
*/
}


text:
angular.module('orderCloud')
	.config(checkoutConfig)
	.controller('CheckoutCtrl', CheckoutController)
	.controller('OrderReviewCtrl', OrderReviewController)
	.controller('OrderConfirmationCtrl', OrderConfirmationController)
    .directive('ordercloudCheckoutLineitems', CheckoutLineItemsListDirective)
    .directive('ordercloudConfirmationLineitems', ConfirmationLineItemsListDirective)
    .controller('CheckoutLineItemsCtrl', CheckoutLineItemsController)
    .controller('ConfirmationLineItemsCtrl', ConfirmationLineItemsController)
    //toggle isMultipleAddressShipping if you do not wish to allow line items to ship to multiple addresses
    .constant('isMultipleAddressShipping', true);
;

function checkoutConfig($stateProvider) {
	$stateProvider
		.state('checkout', {
			parent: 'base',
            data: {componentName: 'Checkout'},
			url: '/checkout',
			templateUrl: 'checkout/templates/checkout.tpl.html',
			controller: 'CheckoutCtrl',
			controllerAs: 'checkout',
			resolve: {
                Order: function($q, $state, toastr, CurrentOrder) {
                    var dfd = $q.defer();
                    CurrentOrder.Get()
                        .then(function(order) {
                            dfd.resolve(order)
                        })
                        .catch(function() {
                            toastr.error('You do not have an active open order.', 'Error');
                            if ($state.current.name.indexOf('checkout') > -1) {
                                $state.go('home');
                            }
                            dfd.reject();
                        });
                    return dfd.promise;
                },
                OrderShipAddress: function($q, OrderShippingAddress) {
                    var dfd = $q.defer();
                    OrderShippingAddress.Get()
                        .then(function(data) {
                            dfd.resolve(data);
                        })
                        .catch(function() {
                            dfd.resolve(null);
                        });
                    return dfd.promise;
                },
                ShippingAddresses: function($q, OrderCloud, Underscore) {
                    var dfd = $q.defer();
                    OrderCloud.Me.ListAddresses()
                        .then(function(data) {
                            dfd.resolve(Underscore.where(data.Items, {Shipping:true}));
                        });
                    return dfd.promise;
                }
			}
		})
        .state('checkout.confirmation', {
            url: '/confirmation',
            views: {
                '@base': {
                    templateUrl: 'checkout/templates/confirmation.tpl.html',
                    controller: 'OrderConfirmationCtrl',
                    controllerAs: 'orderConfirmation'
                }
            }
        })
		.state('orderReview', {
            parent: 'base',
            data: {componentName: 'Checkout'},
			url: '/order/:orderid/review',
            templateUrl: 'checkout/templates/review.tpl.html',
            controller: 'OrderReviewCtrl',
            controllerAs: 'orderReview',
            resolve: {
                SubmittedOrder: function($q, OrderCloud, $stateParams, $state, toastr) {
                    var dfd = $q.defer();
                    OrderCloud.Orders.Get($stateParams.orderid)
                        .then(function(order){
                            if(order.Status == 'Unsubmitted') {
                                $state.go('checkout.shipping')
                                    .then(function() {
                                        toastr.error('You cannot review an Unsubmitted Order', 'Error');
                                        dfd.reject();
                                    });
                            }
                            else dfd.resolve(order);
                        });
                    return dfd.promise;
                }
			}
		})

}

function CheckoutController($state, $rootScope, Order, OrderCloud, ShippingAddresses, OrderShipAddress, OrderShippingAddress) {
    var vm = this;
    vm.currentOrder = Order;
    vm.currentOrder.ShippingAddressID = OrderShipAddress ? OrderShipAddress.ID : null;
    vm.currentOrder.ShippingAddress = OrderShipAddress;
    vm.shippingAddresses = ShippingAddresses;
    vm.isMultipleAddressShipping = true;

    vm.orderIsValid = false;
    if(vm.currentOrder.BillingAddress && vm.currentOrder.BillingAddress.ID != null && vm.currentOrder.PaymentMethod != null){
        vm.orderIsValid = true;
    }

    // default state (if someone navigates to checkout -> checkout.shipping)
    if ($state.current.name === 'checkout') {
        $state.transitionTo('checkout.shipping');
    }

    $rootScope.$on('OrderShippingAddressChanged', function(event, order, address) {
        vm.currentOrder = order;
        vm.currentOrder.ShippingAddressID = address.ID;
        vm.currentOrder.ShippingAddress = address;
    });

    $rootScope.$on('OC:UpdateOrder', function(event, OrderID) {
        OrderCloud.Orders.Get(OrderID)
            .then(function(data) {
                vm.currentOrder.Subtotal = data.Subtotal;
            });
    });

    $rootScope.$on('LineItemAddressUpdated', function() {
        vm.currentOrder.ShippingAddress = null;
        vm.currentOrder.ShippingAddressID = null;
        OrderShippingAddress.Clear();
    });
}

function OrderConfirmationController(Order, CurrentOrder, OrderCloud, $state, isMultipleAddressShipping, $exceptionHandler) {
    var vm = this;
    vm.currentOrder = Order;
    vm.isMultipleAddressShipping = isMultipleAddressShipping;

    vm.submitOrder = function() {
        OrderCloud.Orders.Submit(vm.currentOrder.ID)
            .then(function() {
                CurrentOrder.Remove()
                    .then(function(){
                        $state.go('orderReview', {orderid: vm.currentOrder.ID})
                    })
            })
            .catch(function(ex) {
                $exceptionHandler(ex);
            });
    }
}

function OrderReviewController(SubmittedOrder, isMultipleAddressShipping, OrderCloud, $q, LineItemHelpers) {
	var vm = this;
    vm.submittedOrder = SubmittedOrder;
    vm.isMultipleAddressShipping = isMultipleAddressShipping;

    var dfd = $q.defer();
    var queue = [];
    OrderCloud.LineItems.List(vm.submittedOrder.ID)
        .then(function(li) {
            vm.LineItems = li;
            if (li.Meta.TotalPages > li.Meta.Page) {
                var page = li.Meta.Page;
                while (page < li.Meta.TotalPages) {
                    page += 1;
                    queue.push(OrderCloud.LineItems.List(vm.submittedOrder.ID, page));
                }
            }
            $q.all(queue)
                .then(function(results) {
                    angular.forEach(results, function(result) {
                        vm.LineItems.Items = [].concat(vm.LineItems.Items, result.Items);
                        vm.LineItems.Meta = result.Meta;
                    });
                    dfd.resolve(LineItemHelpers.GetProductInfo(vm.LineItems.Items.reverse()));
                });
        });

    vm.print = function() {
        window.print();
    }

}

function CheckoutLineItemsListDirective() {
    return {
        scope: {
            order: '=',
            addresses: '='
        },
        templateUrl: 'checkout/templates/checkout.lineitems.tpl.html',
        controller: 'CheckoutLineItemsCtrl',
        controllerAs: 'checkoutLI'
    };
}

function CheckoutLineItemsController($scope, $q, OrderCloud, LineItemHelpers, Underscore) {
    var vm = this;
    vm.lineItems = {};
    vm.UpdateQuantity = LineItemHelpers.UpdateQuantity;
    vm.UpdateShipping = LineItemHelpers.UpdateShipping;
    vm.setCustomShipping = LineItemHelpers.CustomShipping;
    vm.RemoveItem = LineItemHelpers.RemoveItem;

    $scope.$on('LineItemAddressUpdated', function(event, LineItemID, address) {
        Underscore.where(vm.lineItems.Items, {ID: LineItemID})[0].ShippingAddress = address;
    });

    $scope.$on('OrderShippingAddressChanged', function(event, order, address) {
        angular.forEach(vm.lineItems.Items, function(li) {
            li.ShippingAddressID = address.ID;
            li.ShippingAddress = address;
        });
    });

    $scope.$watch(function() {
        return $scope.order.ID;
    }, function() {
        LineItemsInit($scope.order.ID)
    });

    function LineItemsInit(OrderID) {
        OrderCloud.LineItems.Get(OrderID)
            .then(function(data) {
                vm.lineItems = data;
                LineItemHelpers.GetProductInfo(vm.lineItems.Items);
            });
    }

    vm.pagingfunction = function() {
        if (vm.lineItems.Meta.Page < vm.lineItems.Meta.TotalPages) {
            var dfd = $q.defer();
            OrderCloud.LineItems.List($scope.order.ID, vm.lineItems.Meta.Page + 1, vm.lineItems.Meta.PageSize)
                .then(function(data) {
                    vm.lineItems.Meta = data.Meta;
                    vm.lineItems.Items = [].concat(vm.lineItems.Items, data.Items);
                    LineItemHelpers.GetProductInfo(vm.lineItems.Items);
                });
            return dfd.promise;
        }
        else return null;
    }
}

function ConfirmationLineItemsListDirective() {
    return {
        scope: {
            order: '='
        },
        templateUrl: 'checkout/templates/confirmation.lineitems.tpl.html',
        controller: 'ConfirmationLineItemsCtrl',
        controllerAs: 'confirmationLI'
    };
}

function ConfirmationLineItemsController($scope, $q, OrderCloud, LineItemHelpers, isMultipleAddressShipping) {
    var vm = this;
    vm.lineItems = {};
    vm.isMultipleAddressShipping = isMultipleAddressShipping;

    $scope.$watch(function() {
        return $scope.order.ID;
    }, function() {
        OrderCloud.LineItems.Get($scope.order.ID)
            .then(function(data) {
                vm.lineItems = data;
                LineItemHelpers.GetProductInfo(vm.lineItems.Items);
            });
    });

    vm.pagingfunction = function() {
        if (vm.lineItems.Meta.Page < vm.lineItems.Meta.TotalPages) {
            var dfd = $q.defer();
            OrderCloud.LineItems.List($scope.order.ID, vm.lineItems.Meta.Page + 1, vm.lineItems.Meta.PageSize)
                .then(function(data) {
                    vm.lineItems.Meta = data.Meta;
                    vm.lineItems.Items = [].concat(vm.lineItems.Items, data.Items);
                    LineItemHelpers.GetProductInfo(vm.lineItems.Items);
                });
            return dfd.promise;
        }
        else return null;
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

class MackTypes extends Pas_Db_Table_Abstract {

    /** The table name
     * @access protected
     * @var string
     */
    protected $_name = 'macktypes';

    /** The primary key
     * @access protected
     * @var int
     */
    protected $_primary = 'id';

    /** Retrieve key value paired dropdown list array
     * @access public
     * @return array $paginator
     */
    public function getMackTypesDD(){
        $select = $this->select()
                ->from($this->_name, array('type', 'type'))
                ->order('type');
        $options = $this->getAdapter()->fetchPairs($select);
        return $options;
    }

    /** Retrieve data for an autocomplete ajax query
     * @access public
     * @param string $q
     * @return array $paginator
     * @todo reckon this can be made more efficient in the controller action
     */
    public function getTypes($q) {
        $types = $this->getAdapter();
        $select = $types->select()
                ->from($this->_name, array('id','term' => 'type'))
                ->where('type LIKE ? ', $q . '%')
                ->order('type')
                ->limit(10);
       return $types->fetchAll($select);
    }

    /** Retrieve paginated mack types
     * @access public
     * @param integer $page
     * @return array $paginator
     */
    public function getMackTypes($params) {
        $types = $this->getAdapter();
        $select = $types->select()
                ->from($this->_name)
                ->joinLeft('coins','coins.mack_type = macktypes.type',array())
                ->order($this->_name . '.type')
                ->group($this->_name . '.type');
        $paginator = Zend_Paginator::factory($select);
        Zend_Paginator::setCache($this->_cache);
        $paginator->setItemCountPerPage(30)
                ->setPageRange(10);
        if(isset($params['page']) && ($params['page'] != "")) {
            $paginator->setCurrentPageNumber($params['page']);
        }
        return $paginator;
    }
}


text:
package com.qubole.quark.planner;

/**
 * Represents a column in a table.
 */
public class QuarkColumn {
  public final String name;
  public final int  type;

  public QuarkColumn(String name, int type) {
    this.name = name.toUpperCase();
    this.type = type;
  }

  public boolean equals(Object obj) {
    if (this == obj) {
      return true;
    }
    if (obj == null) {
      return false;
    }
    if (this.getClass() != obj.getClass()) {
      return false;
    }
    QuarkColumn other = (QuarkColumn) obj;
    return this.name.equals(other.name) && this.type == other.type;
  }

  public int hashCode() {
    return name.hashCode() + type * 31;
  }
}


text:
#!/usr/bin/env node
// @flow

if (!global.__flowTypedBabelPolyfill) {
  require('babel-polyfill');
  global.__flowTypedBabelPolyfill = true;
}

import yargs from 'yargs';
import {fs, path} from './lib/node.js';

import * as Install from './commands/install.js';
import * as CreateStub from './commands/create-stub.js';
import * as RunTests from './commands/runTests.js';
import * as Search from './commands/search.js';
import * as Update from './commands/update.js';
import * as UpdateCache from './commands/update-cache';
import * as ValidateDefs from './commands/validateDefs.js';
import * as Version from './commands/version.js';

import type {Argv} from 'yargs';
import typeof Yargs from 'yargs';

const identity = <T>(x: T): T => x;

export function runCLI() {
  type CommandModule = {
    name: string,
    description: string,
    setup?: (yargs: Yargs) => Yargs,
    // $FlowFixMe
    run: (argv: Argv) => Promise<number>,
  };
  const commands: Array<CommandModule> = [
    CreateStub,
    Install,
    RunTests,
    Search,
    Update,
    UpdateCache,
    ValidateDefs,
    Version,
  ];

  commands
    .reduce(
      (cmdYargs, cmd) =>
        cmdYargs.command(
          cmd.name,
          cmd.description,
          cmd.setup || identity,
          args =>
            cmd
              .run(args, yargs)
              .catch(err => {
                if (err.stack) {
                  console.log('UNCAUGHT ERROR: %s', err.stack);
                } else if (typeof err === 'object' && err !== null) {
                  console.log(
                    'UNCAUGHT ERROR: %s',
                    JSON.stringify(err, null, 2),
                  );
                } else {
                  console.log('UNCAUGHT ERROR:', err);
                }
                process.exit(1);
              })
              .then(code => process.exit(code)),
        ),
      yargs,
    )
    .demand(1)
    .strict()
    .help('h')
    .alias('h', 'help').argv;
}

/**
 * Look to see if the CWD is within an npm project. If it is, and that project
 * has a flow-typed CLI `npm install`ed, use that version instead of the global
 * version of the CLI.
 */
if (require.main === module) {
  const CWD = process.cwd();
  let currDir = CWD;
  let lastDir = null;
  while (currDir !== lastDir) {
    const localCLIPath = path.join(
      currDir,
      'node_modules',
      '.bin',
      'flow-typed',
    );
    try {
      if (fs.statSync(localCLIPath).isFile()) {
        runCLI = require.call(null, localCLIPath).runCLI;
        break;
      }
    } catch (e) {
      /* File doesn't exist, move up a dir... */
    }
    lastDir = currDir;
    currDir = path.resolve(currDir, '..');
  }
  runCLI();
}


text:
package test

import (
	dataTypeInsulin "github.com/tidepool-org/platform/data/types/insulin"
	"github.com/tidepool-org/platform/pointer"
	"github.com/tidepool-org/platform/test"
)

func RandomSimple() *dataTypeInsulin.Simple {
	datum := dataTypeInsulin.NewSimple()
	datum.ActingType = pointer.FromString(test.RandomStringFromArray(dataTypeInsulin.SimpleActingTypes()))
	datum.Brand = pointer.FromString(test.RandomStringFromRange(1, 100))
	datum.Concentration = RandomConcentration()
	return datum
}

func CloneSimple(datum *dataTypeInsulin.Simple) *dataTypeInsulin.Simple {
	if datum == nil {
		return nil
	}
	clone := dataTypeInsulin.NewSimple()
	clone.ActingType = pointer.CloneString(datum.ActingType)
	clone.Brand = pointer.CloneString(datum.Brand)
	clone.Concentration = CloneConcentration(datum.Concentration)
	return clone
}

func NewObjectFromSimple(datum *dataTypeInsulin.Simple, objectFormat test.ObjectFormat) map[string]interface{} {
	if datum == nil {
		return nil
	}
	object := map[string]interface{}{}
	if datum.ActingType != nil {
		object["actingType"] = test.NewObjectFromString(*datum.ActingType, objectFormat)
	}
	if datum.Brand != nil {
		object["brand"] = test.NewObjectFromString(*datum.Brand, objectFormat)
	}
	if datum.Concentration != nil {
		object["concentration"] = NewObjectFromConcentration(datum.Concentration, objectFormat)
	}
	return object
}


text:
package org.apache.hadoop.mapreduce;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.text.NumberFormat;

import org.apache.hadoop.io.Text;

/**
 * JobID represents the immutable and unique identifier for
 * the job. JobID consists of two parts. First part
 * represents the jobtracker identifier, so that jobID to jobtracker map
 * is defined. For cluster setup this string is the jobtracker
 * start time, for local setting, it is "local".
 * Second part of the JobID is the job number.

 * An example JobID is :
 * job_200707121733_0003 , which represents the third job
 * running at the jobtracker started at 200707121733.
 *

 * Applications should never construct or parse JobID strings, but rather
 * use appropriate constructors or {@link #forName(String)} method.
 *
 * @see TaskID
 * @see TaskAttemptID
 * @see org.apache.hadoop.mapred.JobTracker#getNewJobId()
 * @see org.apache.hadoop.mapred.JobTracker#getStartTime()
 */
public class JobID extends org.apache.hadoop.mapred.ID
                   implements Comparable<ID> {
  protected static final String JOB = "job";

  // Jobid regex for various tools and framework components
  public static final String JOBID_REGEX =
    JOB + SEPARATOR + "[0-9]+" + SEPARATOR + "[0-9]+";

  private final Text jtIdentifier;

  protected static final NumberFormat idFormat = NumberFormat.getInstance();
  static {
    idFormat.setGroupingUsed(false);
    idFormat.setMinimumIntegerDigits(4);
  }

  /**
   * Constructs a JobID object
   * @param jtIdentifier jobTracker identifier
   * @param id job number
   */
  public JobID(String jtIdentifier, int id) {
    super(id);
    this.jtIdentifier = new Text(jtIdentifier);
  }

  public JobID() {
    jtIdentifier = new Text();
  }

  public String getJtIdentifier() {
    return jtIdentifier.toString();
  }

  @Override
  public boolean equals(Object o) {
    if (!super.equals(o))
      return false;

    JobID that = (JobID)o;
    return this.jtIdentifier.equals(that.jtIdentifier);
  }

  /**Compare JobIds by first jtIdentifiers, then by job numbers*/
  @Override
  public int compareTo(ID o) {
    JobID that = (JobID)o;
    int jtComp = this.jtIdentifier.compareTo(that.jtIdentifier);
    if(jtComp == 0) {
      return this.id - that.id;
    }
    else return jtComp;
  }

  /**
   * Add the stuff after the "job" prefix to the given builder. This is useful,
   * because the sub-ids use this substring at the start of their string.
   * @param builder the builder to append to
   * @return the builder that was passed in
   */
  public StringBuilder appendTo(StringBuilder builder) {
    builder.append(SEPARATOR);
    builder.append(jtIdentifier);
    builder.append(SEPARATOR);
    builder.append(idFormat.format(id));
    return builder;
  }

  @Override
  public int hashCode() {
    return jtIdentifier.hashCode() + id;
  }

  @Override
  public String toString() {
    return appendTo(new StringBuilder(JOB)).toString();
  }

  @Override
  public void readFields(DataInput in) throws IOException {
    super.readFields(in);
    this.jtIdentifier.readFields(in);
  }

  @Override
  public void write(DataOutput out) throws IOException {
    super.write(out);
    jtIdentifier.write(out);
  }

  /** Construct a JobId object from given string
   * @return constructed JobId object or null if the given String is null
   * @throws IllegalArgumentException if the given string is malformed
   */
  public static JobID forName(String str) throws IllegalArgumentException {
    if(str == null)
      return null;
    try {
      String[] parts = str.split("_");
      if(parts.length == 3) {
        if(parts[0].equals(JOB)) {
          return new org.apache.hadoop.mapred.JobID(parts[1],
                                                    Integer.parseInt(parts[2]));
        }
      }
    }catch (Exception ex) {//fall below
    }
    throw new IllegalArgumentException("JobId string : " + str
        + " is not properly formed");
  }

}


text:
<?php

namespace Twig\Node\Expression\Unary;

require __DIR__.'/../../../../lib/Twig/Node/Expression/Unary/Pos.php';

if (\false) {
    class PosUnary extends \Twig_Node_Expression_Unary_Pos
    {
    }
}


text:
namespace Js
{
    class LiteralStringWithPropertyStringPtr : public LiteralString
    {
    private:
        Field(PropertyString*) propertyString;
        Field(const Js::PropertyRecord*) propertyRecord;

    public:
        virtual void GetPropertyRecord(_Out_ PropertyRecord const** propRecord, bool dontLookupFromDictionary = false) override;

        bool HasPropertyRecord() const { return propertyRecord != nullptr; }

        PropertyString * GetPropertyString() const;
        PropertyString * GetOrAddPropertyString(); // Get if it's there, otherwise bring it in.
        void SetPropertyString(PropertyString * propStr);

        template <typename StringType> static LiteralStringWithPropertyStringPtr * ConvertString(StringType * originalString);

        static uint GetOffsetOfPropertyString() { return offsetof(LiteralStringWithPropertyStringPtr, propertyString); }
        static bool Is(Var var);
        static bool Is(RecyclableObject* var);
        template <typename T> static LiteralStringWithPropertyStringPtr* TryFromVar(T var);

        static JavascriptString *
        NewFromCString(const char * cString, const CharCount charCount, JavascriptLibrary *const library);

        static JavascriptString *
        NewFromWideString(const char16 * wString, const CharCount charCount, JavascriptLibrary *const library);

        static JavascriptString * CreateEmptyString(JavascriptLibrary *const library);

    protected:
        LiteralStringWithPropertyStringPtr(StaticType* stringTypeStatic);
        LiteralStringWithPropertyStringPtr(const char16 * wString, const CharCount stringLength, JavascriptLibrary *const library);

        DEFINE_VTABLE_CTOR(LiteralStringWithPropertyStringPtr, LiteralString);

    public:
        virtual VTableValue DummyVirtualFunctionToHinderLinkerICF()
        {
            return VTableValue::VtableLiteralStringWithPropertyStringPtr;
        }
    };

    // Templated so that the Is call dispatchs to different function depending
    // on if argument is already a RecyclableObject* or only known to be a Var
    //
    // In case it is known to be a RecyclableObject*, the Is call skips that check
    template <typename T>
    inline LiteralStringWithPropertyStringPtr * LiteralStringWithPropertyStringPtr::TryFromVar(T var)
    {
        return LiteralStringWithPropertyStringPtr::Is(var)
            ? reinterpret_cast<LiteralStringWithPropertyStringPtr*>(var)
            : nullptr;
    }

    // Base class for concat strings.
    // Concat string is a virtual string, or a non-leaf node in concat string tree.
    // It does not hold characters by itself but has one or more child nodes.
    // Only leaf nodes (which are not concat strings) hold the actual characters.
    // The flattening happens on demand (call GetString() or GetSz()),
    // until then we don't create actual big char16* buffer, just keep concat tree as a tree.
    // The result of flattening the concat string tree is concat of all leaf nodes from left to right.
    // Usage pattern:
    //   // Create concat tree using one of non-abstract derived classes.
    //   JavascriptString* result = concatTree->GetString();    // At this time we flatten the tree into 1 actual wchat_t* string.
    class ConcatStringBase _ABSTRACT : public LiteralString // vtable will be switched to LiteralString's vtable after flattening
    {
        friend JavascriptString;

    protected:
        ConcatStringBase(StaticType* stringTypeStatic);
        DEFINE_VTABLE_CTOR_ABSTRACT(ConcatStringBase, LiteralString);

        virtual void CopyVirtual(_Out_writes_(m_charLength) char16 *const buffer,
            StringCopyInfoStack &nestedStringTreeCopyInfos, const byte recursionDepth) = 0;
        void CopyImpl(_Out_writes_(m_charLength) char16 *const buffer,
            int itemCount, _In_reads_(itemCount) JavascriptString * const * items,
            StringCopyInfoStack &nestedStringTreeCopyInfos, const byte recursionDepth);

        // Subclass can call this to implement GetSz and use the actual type to avoid virtual call to Copy.
        template <typename ConcatStringType> const char16 * GetSzImpl();
    public:
        virtual const char16* GetSz() = 0;     // Force subclass to call GetSzImpl with the real type to avoid virtual calls
        using JavascriptString::Copy;
        virtual bool IsTree() const override sealed;
    };

    // Concat string with N (or less) child nodes.
    // Use it when you know the number of children at compile time.
    // There could be less nodes than N. When we find 1st NULL node going incrementing the index,
    // we see this as indication that the rest on the right are empty and stop iterating.
    // Usage pattern:
    //   ConcatStringN<3>* tree = ConcatStringN<3>::New(scriptContext);
    //   tree->SetItem(0, javascriptString1);
    //   tree->SetItem(1, javascriptString2);
    //   tree->SetItem(2, javascriptString3);
    template <int N>
    class ConcatStringN : public ConcatStringBase
    {
        friend JavascriptString;

    protected:
        ConcatStringN(StaticType* stringTypeStatic, bool doZeroSlotsAndLength = true);
        DEFINE_VTABLE_CTOR(ConcatStringN<N>, ConcatStringBase);

        virtual void CopyVirtual(_Out_writes_(m_charLength) char16 *const buffer, StringCopyInfoStack &nestedStringTreeCopyInfos, const byte recursionDepth) override
        {
#pragma prefast(suppress: __WARNING_POTENTIAL_BUFFER_OVERFLOW_HIGH_PRIORITY, "WDGVSO:14980704 The CopyImpl method uses GetLength() to ensure we only access m_charLength elements of buffer.")
            __super::CopyImpl(buffer, N, AddressOf(m_slots[0]), nestedStringTreeCopyInfos, recursionDepth);
        }
        virtual int GetRandomAccessItemsFromConcatString(Js::JavascriptString * const *& items) const
        {
            items = AddressOf(m_slots[0]);
            return N;
        }

    public:
        static ConcatStringN<N>* New(ScriptContext* scriptContext);
        const char16 * GetSz() override sealed;
        void SetItem(_In_range_(0, N - 1) int index, JavascriptString* value);

    protected:
        Field(JavascriptString*) m_slots[N];   // These contain the child nodes. 1 slot is per 1 item (JavascriptString*).
    };

    // Concat string that uses binary tree, each node has 2 children.
    // Usage pattern:
    //   ConcatString* str = ConcatString::New(javascriptString1, javascriptString2);
    // Note: it's preferred you would use the following for concats, that would figure out whether concat string is optimal or create a new string is better.
    //   JavascriptString::Concat(javascriptString1, javascriptString2);
    class ConcatString sealed : public ConcatStringN<2>
    {
        ConcatString(JavascriptString* a, JavascriptString* b);
    protected:
        DEFINE_VTABLE_CTOR(ConcatString, ConcatStringN<2>);
    public:
        static ConcatString* New(JavascriptString* a, JavascriptString* b);
        static const int MaxDepth = 1000;

        JavascriptString *LeftString() const { Assert(!IsFinalized()); return m_slots[0]; }
        JavascriptString *RightString() const { Assert(!IsFinalized()); return m_slots[1]; }
    };

    // Concat string with any number of child nodes, can grow dynamically.
    // Usage pattern:
    //   ConcatStringBuilder* tree = ConcatStringBuider::New(scriptContext, 5);
    //   tree->Append(javascriptString1);
    //   tree->Append(javascriptString2);
    //   ...
    // Implementation details:
    // - uses chunks, max chunk size is specified by c_maxChunkSlotCount, until we fit into that, we realloc, otherwise create new chunk.
    // - We use chunks in order to avoid big allocations, we don't expect lots of reallocs, that why chunk size is relatively big.
    // - the chunks are linked using m_prevChunk field. flattening happens from left to right, i.e. first we need to get
    //   head chunk -- the one that has m_prevChunk == NULL.
    class ConcatStringBuilder sealed : public ConcatStringBase
    {
        friend JavascriptString;
        ConcatStringBuilder(ScriptContext* scriptContext, int initialSlotCount);
        ConcatStringBuilder(const ConcatStringBuilder& other);
        void AllocateSlots(int requestedSlotCount);
        ConcatStringBuilder* GetHead() const;

    protected:
        DEFINE_VTABLE_CTOR(ConcatStringBuilder, ConcatStringBase);
        virtual void CopyVirtual(_Out_writes_(m_charLength) char16 *const buffer, StringCopyInfoStack &nestedStringTreeCopyInfos, const byte recursionDepth) override sealed;

    public:
        static ConcatStringBuilder* New(ScriptContext* scriptContext, int initialSlotCount);
        const char16 * GetSz() override sealed;
        void Append(JavascriptString* str);

    private:
        // MAX number of slots in one chunk. Until we fit into this, we realloc, otherwise create new chunk.
        static const int c_maxChunkSlotCount = 1024;
        int GetItemCount() const;

        Field(Field(JavascriptString*)*) m_slots; // Array of child nodes.
        Field(int) m_slotCount;   // Number of allocated slots (1 slot holds 1 item) in this chunk.
        Field(int) m_count;       // Actual number of items in this chunk.
        Field(ConcatStringBuilder*) m_prevChunk;
    };

    // Concat string that wraps another string.
    // Use it when you need to wrap something with e.g. { and }.
    // Usage pattern:
    //   result = ConcatStringWrapping<_u('{'), _u('}')>::New(result);
    template <char16 L, char16 R>
    class ConcatStringWrapping sealed : public ConcatStringBase
    {
        friend JavascriptString;
        ConcatStringWrapping(JavascriptString* inner);
        JavascriptString* GetFirstItem() const;
        JavascriptString* GetLastItem() const;

    protected:
        DEFINE_VTABLE_CTOR(ConcatStringWrapping, ConcatStringBase);
        virtual void CopyVirtual(_Out_writes_(m_charLength) char16 *const buffer, StringCopyInfoStack &nestedStringTreeCopyInfos, const byte recursionDepth) override sealed
        {
            const_cast<ConcatStringWrapping *>(this)->EnsureAllSlots();
#pragma prefast(suppress: __WARNING_POTENTIAL_BUFFER_OVERFLOW_HIGH_PRIORITY, "WDGVSO:14980704 The CopyImpl method uses GetLength() to ensure we only access m_charLength elements of buffer.")
            __super::CopyImpl(buffer, _countof(m_slots), AddressOf(m_slots[0]), nestedStringTreeCopyInfos, recursionDepth);
        }
        virtual int GetRandomAccessItemsFromConcatString(Js::JavascriptString * const *& items) const override sealed
        {
            const_cast<ConcatStringWrapping *>(this)->EnsureAllSlots();
            items = AddressOf(m_slots[0]);
            return _countof(m_slots);
        }
    public:
        static ConcatStringWrapping<L, R>* New(JavascriptString* inner);
        const char16 * GetSz() override sealed;
    private:
        void EnsureAllSlots()
        {
            m_slots[0] = this->GetFirstItem();
            m_slots[1] = m_inner;
            m_slots[2] = this->GetLastItem();
        }

        Field(JavascriptString *) m_inner;

        // Use the padding space for the concat
        Field(JavascriptString *) m_slots[3];
    };

    // Make sure the padding doesn't add tot he size of ConcatStringWrapping
#if defined(TARGET_64)
    CompileAssert(sizeof(ConcatStringWrapping<_u('"'), _u('"')>) == 64);
#else
    CompileAssert(sizeof(ConcatStringWrapping<_u('"'), _u('"')>) == 32);
#endif

    // Concat string with N child nodes. Use it when you don't know the number of children at compile time.
    // Usage pattern:
    //   ConcatStringMulti* tree = ConcatStringMulti::New(3, scriptContext);
    //   tree->SetItem(0, javascriptString1);
    //   tree->SetItem(1, javascriptString2);
    //   tree->SetItem(2, javascriptString3);
    class ConcatStringMulti sealed : public ConcatStringBase
    {
        friend JavascriptString;

    protected:
        ConcatStringMulti(uint slotCount, JavascriptString * a1, JavascriptString * a2, StaticType* stringTypeStatic);
        DEFINE_VTABLE_CTOR(ConcatStringMulti, ConcatStringBase);

        virtual void CopyVirtual(_Out_writes_(m_charLength) char16 *const buffer, StringCopyInfoStack &nestedStringTreeCopyInfos, const byte recursionDepth) override
        {
            Assert(IsFilled());
#pragma prefast(suppress: __WARNING_POTENTIAL_BUFFER_OVERFLOW_HIGH_PRIORITY, "WDGVSO:14980704 The CopyImpl method uses GetLength() to ensure we only access m_charLength elements of buffer.")
            __super::CopyImpl(buffer, slotCount, AddressOf(m_slots[0]), nestedStringTreeCopyInfos, recursionDepth);
        }
        virtual int GetRandomAccessItemsFromConcatString(Js::JavascriptString * const *& items) const
        {
            Assert(IsFilled());
            items = AddressOf(m_slots[0]);
            return slotCount;
        }

    public:
        static ConcatStringMulti * New(uint slotCount, JavascriptString * a1, JavascriptString * a2, ScriptContext* scriptContext);
        const char16 * GetSz() override sealed;
        static bool Is(Var var);
        static ConcatStringMulti * FromVar(Var value);
        static ConcatStringMulti * UnsafeFromVar(Var value);
        static size_t GetAllocSize(uint slotCount);
        void SetItem(_In_range_(0, slotCount - 1) uint index, JavascriptString* value);

        static uint32 GetOffsetOfSlotCount() { return offsetof(ConcatStringMulti, slotCount); }
        static uint32 GetOffsetOfSlots() { return offsetof(ConcatStringMulti, m_slots); }
    protected:
        Field(uint) slotCount;
        Field(uint)   __alignment;
        Field(size_t) __alignmentPTR;
        Field(JavascriptString*) m_slots[];   // These contain the child nodes.

#if DBG
        bool IsFilled() const;
#endif

    public:
        virtual VTableValue DummyVirtualFunctionToHinderLinkerICF()
        {
            return VTableValue::VtableConcatStringMulti;
        }
    };
}


text:
{-# LANGUAGE OverloadedStrings, TupleSections, CPP #-}
-- | Utilities for validating and inspecting Selda tables.
module Database.Selda.Validation
  ( TableDiff (..), ColumnDiff (..)
  , TableName, ColName, ColumnInfo, SqlTypeRep, tableInfo
  , showTableDiff, showColumnDiff
  , describeTable, diffTable, diffTables
  , validateTable, validateSchema
  ) where
import Control.Monad.Catch ( MonadThrow(..) )
import Data.List ((\\))
import Data.Maybe (catMaybes)
import Data.Text (pack, unpack, intercalate)
import Database.Selda
    ( Text,
      MonadIO(liftIO),
      TableName,
      ColName,
      Table(..),
      MonadSelda )
import Database.Selda.Backend.Internal
    ( SqlTypeRep(TInt64, TRowID),
      SeldaBackend(getTableInfo),
      ColumnInfo(colType, colIsAutoPrimary, colIsNullable, colHasIndex,
                 colFKs, colName),
      TableInfo(tableColumnInfos, tableUniqueGroups, tablePrimaryKey),
      tableInfo,
      withBackend )
import Database.Selda.Types ( fromColName, fromTableName )
import Database.Selda.Table.Type (tableCols)
import Database.Selda.Table.Validation (ValidationError (..), validateOrThrow)

-- | Are the given types compatible?
isCompatibleWith :: SqlTypeRep -> SqlTypeRep -> Bool
isCompatibleWith TRowID TInt64 = True
isCompatibleWith TInt64 TRowID = True
isCompatibleWith a b         = a == b

-- | Validate a table schema, and check it for consistency against the current
--   database.
--   Throws a 'ValidationError' if the schema does not validate, or if
--   inconsistencies were found.
validateTable :: (MonadSelda m, MonadThrow m) => Table a -> m ()
validateTable t = do
  validateSchema t
  diffs <- diffTable t
  case diffs of
    TableOK -> return ()
    errors  -> throwM $ ValidationError $ concat
      [ "error validating table ", unpack (fromTableName (tableName t)), ":\n"
      , show errors
      ]

-- | Ensure that the schema of the given table is valid.
--   Does not ensure consistency with the current database.
validateSchema :: MonadThrow m => Table a -> m ()
validateSchema t = validateOrThrow (tableName t) (tableCols t) `seq` return ()

-- | A description of the difference between a schema and its corresponding
--   database table.
data TableDiff
  = TableOK
  | TableMissing
  | UniqueMissing [[ColName]]
  | UniquePresent [[ColName]]
  | PkMissing [ColName]
  | PkPresent [ColName]
  | InconsistentColumns [(ColName, [ColumnDiff])]
    deriving Eq
instance Show TableDiff where
  show = unpack . showTableDiff

-- | A description of the difference between a column in a Selda table and its
--   corresponding database column.
data ColumnDiff
  = ColumnMissing
  | ColumnPresent
  | NameMismatch ColName
  | UnknownType Text
  | TypeMismatch SqlTypeRep SqlTypeRep
  | AutoIncrementMismatch Bool
  | NullableMismatch Bool
  | ForeignKeyMissing TableName ColName
  | ForeignKeyPresent TableName ColName
  | IndexMismatch Bool
    deriving Eq

instance Show ColumnDiff where
  show = unpack . showColumnDiff

-- | Pretty-print a table diff.
showTableDiff :: TableDiff -> Text
showTableDiff TableOK = "no inconsistencies detected"
showTableDiff TableMissing = "table does not exist"
showTableDiff (UniqueMissing cs) = mconcat
  [ "table should have uniqueness constraints on the following column groups, "
  , "but doesn't in database:\n"
  , intercalate ", "
    [ "(" <> intercalate ", " (map fromColName constraintGroup) <> ")"
    | constraintGroup <- cs
    ]
  ]
showTableDiff (UniquePresent cs) = mconcat
  [ "table shouldn't have uniqueness constraints on the following column groups, "
  , "but does in database:\n"
  , intercalate ", "
    [ "(" <> intercalate ", " (map fromColName constraintGroup) <> ")"
    | constraintGroup <- cs
    ]
  ]
showTableDiff (PkMissing cs) = mconcat
  [ "table should have a primary key constraint on the following column group, "
  , "but doesn't in database:\n"
  , "(" <> intercalate ", " (map fromColName cs) <> ")"
  ]
showTableDiff (PkPresent cs) = mconcat
  [ "table shouldn't have a primary key constraint group, "
  , "but does in database:\n"
  , "(" <> intercalate ", " (map fromColName cs) <> ")"
  ]
showTableDiff (InconsistentColumns cols) = mconcat
  [ "table has inconsistent columns:\n"
  , mconcat (map showColDiffs cols)
  ]
  where
    showColDiffs (col, diffs) = mconcat
      [ "  ", fromColName col, ":\n"
      , mconcat (map showDiffs diffs)
      ]
    showDiffs diff = mconcat
      [ "    ", showColumnDiff diff, "\n"
      ]

-- | Pretty-print a column diff.
showColumnDiff :: ColumnDiff -> Text
showColumnDiff ColumnMissing =
  "column does not exist in database"
showColumnDiff ColumnPresent =
  "column exists in database even though it shouldn't"
showColumnDiff (NameMismatch n) =
  mconcat ["column is called ", fromColName n, " in database"]
showColumnDiff (UnknownType t) =
  mconcat ["column has incompatible type \"", t, "\" in database"]
showColumnDiff (TypeMismatch t1 t2) =
  mconcat [ "column should have type `", pack (show t1)
          , "', but actually has type `", pack (show t2)
          , "' in database"
          ]
showColumnDiff (ForeignKeyMissing tbl col) =
  mconcat [ "column should be a foreign key referencing column "
          , fromColName col, " of table ", fromTableName tbl
          , "', but isn't a foreign key in database"
          ]
showColumnDiff (ForeignKeyPresent tbl col) =
  mconcat [ "column is a foreign key referencing column "
          , fromColName col, " of table ", fromTableName tbl
          , ", in database, even though it shouldn't be"
          ]
showColumnDiff (AutoIncrementMismatch dbval) =
  showBoolDiff dbval "auto-incrementing"
showColumnDiff (NullableMismatch dbval) =
  showBoolDiff dbval "nullable"
showColumnDiff (IndexMismatch dbval) =
  showBoolDiff dbval "indexed"

showBoolDiff :: Bool -> Text -> Text
showBoolDiff True what =
  mconcat ["column is ", what, " in database, even though it shouldn't be"]
showBoolDiff False what =
  mconcat ["column is not ", what, " in database, even though it should be"]

-- | Get a description of the table by the given name currently in the database.
describeTable :: MonadSelda m => TableName -> m TableInfo
describeTable tbl = withBackend (liftIO . flip getTableInfo tbl)

-- | Check the given table for consistency with the current database, returning
--   a description of all inconsistencies found.
--   The table schema itself is not validated beforehand.
diffTable :: MonadSelda m => Table a -> m TableDiff
diffTable tbl = do
  dbInfos <- describeTable (tableName tbl)
  return $ diffColumns (tableInfo tbl) dbInfos

-- | Compute the difference between the two given tables.
--   The first table is considered to be the schema, and the second the database.
diffTables :: Table a -> Table b -> TableDiff
diffTables schema db = diffColumns (tableInfo schema) (tableInfo db)

-- | Compute the difference between the columns of two tables.
--   The first table is considered to be the schema, and the second the database.
diffColumns :: TableInfo -> TableInfo -> TableDiff
diffColumns inschema indb =
    case ( zipWith diffColumn infos dbInfos
         , map colName infos \\ map colName dbInfos
         , map colName dbInfos \\ map colName infos
         , tableUniqueGroups inschema \\ tableUniqueGroups indb
         , tableUniqueGroups indb \\ tableUniqueGroups inschema
         , tablePrimaryKey inschema \\ tablePrimaryKey indb
         , tablePrimaryKey indb \\ tablePrimaryKey inschema) of
      ([], _, _, _, _, _, _) ->
        TableMissing
      (diffs, [], [], [], [], [], []) | all consistent diffs ->
        TableOK
      (diffs, missing, extras, [], [], [], []) ->
        InconsistentColumns $ concat
          [ filter (not . consistent) diffs
          , map (, [ColumnMissing]) missing
          , map (, [ColumnPresent]) extras
          ]
      (_, _, _, schemaUniques, [], [], []) ->
        UniqueMissing schemaUniques
      (_, _, _, _, dbUniques, [], []) ->
        UniquePresent dbUniques
      (_, _, _, _, _, schemaPks, []) ->
        PkMissing schemaPks
      (_, _, _, _, _, _, dbPks) ->
        PkPresent dbPks
  where
    infos = tableColumnInfos inschema
    dbInfos = tableColumnInfos indb
    consistent (_, diffs) = null diffs
    diffColumn schema db = (colName schema, catMaybes
      ([ check colName NameMismatch
       , case colType db of
           Left typ ->
             Just (UnknownType typ)
           Right t | not (t `isCompatibleWith` schemaColType) ->
             Just (TypeMismatch schemaColType t)
           _ ->
             Nothing
       , check colIsAutoPrimary AutoIncrementMismatch
       , check colIsNullable NullableMismatch
       , check colHasIndex IndexMismatch
       ] ++ mconcat
       [ map (Just . uncurry ForeignKeyPresent)
             (colFKs schema \\ colFKs db)
       , map (Just . uncurry ForeignKeyMissing)
             (colFKs db \\ colFKs schema)
       ]))
      where
        schemaColType = case colType schema of
          Right t -> t
          Left t -> error $ "Selda has no idea what to make of this type: " ++ show t
        check :: Eq a
              => (ColumnInfo -> a)
              -> (a -> ColumnDiff)
              -> Maybe ColumnDiff
        check f err
          | f schema == f db = Nothing
          | otherwise        = Just (err (f db))


text:
You can use ArcGIS Online to control who can view your data items. Items can be [shared](http://doc.arcgis.com/en/arcgis-online/share-maps/share-items.htm) with groups, organizations or just kept private for you to view.

In this lab you will explore how to share layers.

NOTE: If you don't have any data items in your account, go to [Import Data](../import_data/lab.md) first.

###Steps

1. Go to [arcgis.com](http://www.arcgis.com) and login.

2. Click `My Content`.

3. In `My Content`, select one of your Feature Layers (data items).

4. Select `Share` and explore the sharing options then share your data.

###Bonus
* You can also share items to groups. Use ArcGIS Online to search for groups that have shared items.


text:
package com.garry.heheweather.gson;

import com.google.gson.annotations.SerializedName;

/**
 * Created by 颜伟凡 on 2017/5/28.
 */

public class Now {
    @SerializedName("tmp")
    public String temperature;
    @SerializedName("cond")
    public More more;
    public class More{
        @SerializedName("txt")
        public String info;
    }
}


text:
<?php

/*
BioWarehouseToKnowledgeBase.php
   Writes knowledgeBase data stored in BioWarehouse database to excel file.

   Instructions for building knowledgeBase:
   I.   Load BioWarehouse data into excel file -- BioWarehouseToKnowledgeBase.php
   II.  Edit knowledgeBase file (excel)
   III. Save knowledgeBase file -- knowledgeBaseToBioWarehouse.php

   Repeat steps I-III as necessary.

   Author: Jonathan Karr
   Affiliation: Covert Lab, Department of Bioengineering, Stanford University
   Last Updated: 1/31/2011
*/

//*********************
//increase memory available to php
//*********************
ini_set('memory_limit', '1024M');

//*********************
//include classes
//*********************
set_include_path(get_include_path() . PATH_SEPARATOR . 'lib');

require_once 'library.php';
require_once '../pageTemplate.php';
require_once 'src/include.php';

//*********************
//initialize session
//*********************
if (count($argv) >= 4){
	$userName = $argv[2];
	$password = $argv[3];
	require('configuration.php');

	session_start();

	$link = databaseConnect($configuration);
	$result = mysql_query(sprintf("CALL loginuser('%s', '%s')", $userName, $password)) or die(mysql_error());
	if (mysql_num_rows($result) == 0){
		session_unset();
		echo "Invalid username and/or password.\n";
		exit;
	}
	$user = mysql_fetch_array($result);
	mysql_close($link);

	$_SESSION['UserName'] = $userName;
	$_SESSION['UserID'] = $user['ID'];
}

//*********************
//download knowledge base
//*********************
$knowledgeBase = new KnowledgeBase();
if ($argv[1] == 'latest')
	$knowledgeBase->findWID('', '');
else
	$knowledgeBase->selectWID();
if (false === $knowledgeBase->loadFromDatabase(true)) exit;
$knowledgeBase->exportXLS(true);

?>


text:
import { foreach } from "../../func/util";
import sort from "./sort.js";
import general from "./general";
import { trueFunc, falseFunc } from "./util";

/*
	compiles a selector to an executable function
*/

function compileRules ( rules, context ) {
	const acceptSelf = rules [ 0 ].name === "scope" && rules [ 1 ].type === "descendant";
	return rules.reduce ( ( func, rule, index ) => {
		if ( func === falseFunc ) {
			return func;
		}

		return general [ rule.type ] ( func, rule, context, acceptSelf && index === 1 );
	}, trueFunc );
}

function reduceRules ( a, b ) {
	if ( b === falseFunc || a === trueFunc ) {
		return a;
	}
	if ( a === falseFunc || b === trueFunc ) {
		return b;
	}

	return elem => {
		return a ( elem ) || b ( elem );
	};
}

export default function compileToken ( token, context ) {

    // 不查找伪类和::selection
    foreach ( token, t => {
    	foreach ( t, ( item, i ) => {
    		if ( item.type === "pseudo" || item.type === "pseudo-element" ) {
    			t.splice ( i, 1 );
    		}
    	} );
    } );
	token.forEach ( sort );

	return token
		.map ( rules => compileRules ( rules, context ) )
		.reduce ( reduceRules, falseFunc );
}


text:
package com.arjuna.databroker.webportal.store;

import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import org.hibernate.annotations.GenericGenerator;

@Entity
public class DataBrokerEntity implements Serializable
{
    private static final long serialVersionUID = 6595365591149062175L;

    public DataBrokerEntity()
    {
    }

    public DataBrokerEntity(String name, String summary, String serviceRootURL, String requesterId)
    {
        _name           = name;
        _summary        = summary;
        _serviceRootURL = serviceRootURL;
        _requesterId    = requesterId;
    }

    public String getId()
    {
        return _id;
    }

    public void setId(String id)
    {
        _id = id;
    }

    public String getName()
    {
        return _name;
    }

    public void setName(String name)
    {
        _name = name;
    }

    public String getSummary()
    {
        return _summary;
    }

    public void setSummary(String summary)
    {
        _summary = summary;
    }

    public String getServiceRootURL()
    {
        return _serviceRootURL;
    }

    public void setServiceRootURL(String serviceRootURL)
    {
        _serviceRootURL = serviceRootURL;
    }

    public String getRequesterId()
    {
        return _requesterId;
    }

    public void setRequesterId(String requesterId)
    {
        _requesterId = requesterId;
    }

    @Id
    @Column(name = "id")
    @GeneratedValue(generator = "system-uuid")
    @GenericGenerator(name = "system-uuid", strategy = "uuid2")
    protected String _id;

    @Column(name = "name")
    private String _name;

    @Column(name = "summary")
    private String _summary;

    @Column(name = "serviceRootURL")
    private String _serviceRootURL;

    @Column(name = "requesterId")
    private String _requesterId;
}


text:
package org.onosproject.cluster;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;

/**
 * Test adapter for leadership service.
 */
public class LeadershipServiceAdapter implements LeadershipService {

    @Override
    public NodeId getLeader(String path) {
        return null;
    }

    @Override
    public Leadership getLeadership(String path) {
        return null;
    }

    @Override
    public Set<String> ownedTopics(NodeId nodeId) {
        return null;
    }

    @Override
    public CompletableFuture<Leadership> runForLeadership(String path) {
        return null;
    }

    @Override
    public CompletableFuture<Void> withdraw(String path) {
        return null;
    }

    @Override
    public Map<String, Leadership> getLeaderBoard() {
        return null;
    }

    @Override
    public void addListener(LeadershipEventListener listener) {

    }

    @Override
    public void removeListener(LeadershipEventListener listener) {

    }

    @Override
    public Map<String, List<NodeId>> getCandidates() {
        return null;
    }

    @Override
    public List<NodeId> getCandidates(String path) {
        return null;
    }

    @Override
    public boolean stepdown(String path) {
        return false;
    }

    @Override
    public boolean makeTopCandidate(String path, NodeId nodeId) {
        return false;
    }
}


text:
<title>Downloading GCC</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="Downloading GCC">
<meta name="generator" content="makeinfo 4.11">
<link title="Top" rel="top" href="#Top">
<link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage">

<meta http-equiv="Content-Style-Type" content="text/css">

Downloading GCC

GCC is distributed via SVN and FTP
tarballs compressed with <samp>gzip</samp> or
<samp>bzip2</samp>.

Please refer to the releases web page
for information on how to obtain GCC.

The source distribution includes the C, C++, Objective-C, Fortran, Java,
and Ada (in the case of GCC 3.1 and later) compilers, as well as
runtime libraries for C++, Objective-C, Fortran, and Java.
For previous versions these were downloadable as separate components such
as the core GCC distribution, which included the C language front end and
shared components, and language-specific distributions including the
language front end and the language runtime (where appropriate).

If you also intend to build binutils (either to upgrade an existing
installation or for use in place of the corresponding tools of your
OS), unpack the binutils distribution either in the same directory or
a separate one.  In the latter case, add symbolic links to any
components of the binutils you intend to build alongside the compiler
(<samp>bfd</samp>, <samp>binutils</samp>, <samp>gas</samp>, <samp>gprof</samp>, <samp>ld</samp>,
<samp>opcodes</samp>, ...) to the directory containing the GCC sources.

Likewise the GMP, MPFR and MPC libraries can be automatically built
together with GCC.  Unpack the GMP, MPFR and/or MPC source
distributions in the directory containing the GCC sources and rename
their directories to <samp>gmp</samp>, <samp>mpfr</samp> and <samp>mpc</samp>,
respectively (or use symbolic links with the same name).

Return to the GCC Installation page


text:
<?php

namespace Tests\Functional;

class HomepageTest extends BaseTestCase
{
    /**
     * Test that the index route returns a rendered response.
     */
    public function testGetHomepageWithoutName()
    {
        $this->withMiddleware = false;
        $response = $this->runApp('GET', '/');
        $this->assertEquals(200, $response->getStatusCode());
    }

    /**
     * Test that the index route won't accept a post request
     */
    public function testPostHomepageNotAllowed()
    {
        $this->withMiddleware = false;
        $response = $this->runApp('POST', '/', ['test']);

        $this->assertEquals(405, $response->getStatusCode());
        $this->assertContains('Method not allowed', (string)$response->getBody());
    }

}


text:
#include <aws/securityhub/model/AwsElasticsearchDomainElasticsearchClusterConfigZoneAwarenessConfigDetails.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace SecurityHub
{
namespace Model
{

AwsElasticsearchDomainElasticsearchClusterConfigZoneAwarenessConfigDetails::AwsElasticsearchDomainElasticsearchClusterConfigZoneAwarenessConfigDetails() :
    m_availabilityZoneCount(0),
    m_availabilityZoneCountHasBeenSet(false)
{
}

AwsElasticsearchDomainElasticsearchClusterConfigZoneAwarenessConfigDetails::AwsElasticsearchDomainElasticsearchClusterConfigZoneAwarenessConfigDetails(JsonView jsonValue) :
    m_availabilityZoneCount(0),
    m_availabilityZoneCountHasBeenSet(false)
{
  *this = jsonValue;
}

AwsElasticsearchDomainElasticsearchClusterConfigZoneAwarenessConfigDetails& AwsElasticsearchDomainElasticsearchClusterConfigZoneAwarenessConfigDetails::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("AvailabilityZoneCount"))
  {
    m_availabilityZoneCount = jsonValue.GetInteger("AvailabilityZoneCount");

    m_availabilityZoneCountHasBeenSet = true;
  }

  return *this;
}

JsonValue AwsElasticsearchDomainElasticsearchClusterConfigZoneAwarenessConfigDetails::Jsonize() const
{
  JsonValue payload;

  if(m_availabilityZoneCountHasBeenSet)
  {
   payload.WithInteger("AvailabilityZoneCount", m_availabilityZoneCount);

  }

  return payload;
}

} // namespace Model
} // namespace SecurityHub
} // namespace Aws


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;

namespace Microsoft.Scripting.Interpreter {
    internal abstract class GreaterThanInstruction : Instruction {
        private static Instruction _SByte, _Int16, _Char, _Int32, _Int64, _Byte, _UInt16, _UInt32, _UInt64, _Single, _Double;

        public override int ConsumedStack { get { return 2; } }
        public override int ProducedStack { get { return 1; } }

        private GreaterThanInstruction() {
        }

        internal sealed class GreaterThanSByte : GreaterThanInstruction {
            public override int Run(InterpretedFrame frame) {
                SByte right = (SByte)frame.Pop();
                frame.Push(((SByte)frame.Pop()) > right);
                return +1;
            }
        }

        internal sealed class GreaterThanInt16 : GreaterThanInstruction {
            public override int Run(InterpretedFrame frame) {
                Int16 right = (Int16)frame.Pop();
                frame.Push(((Int16)frame.Pop()) > right);
                return +1;
            }
        }

        internal sealed class GreaterThanChar : GreaterThanInstruction {
            public override int Run(InterpretedFrame frame) {
                Char right = (Char)frame.Pop();
                frame.Push(((Char)frame.Pop()) > right);
                return +1;
            }
        }

        internal sealed class GreaterThanInt32 : GreaterThanInstruction {
            public override int Run(InterpretedFrame frame) {
                Int32 right = (Int32)frame.Pop();
                frame.Push(((Int32)frame.Pop()) > right);
                return +1;
            }
        }

        internal sealed class GreaterThanInt64 : GreaterThanInstruction {
            public override int Run(InterpretedFrame frame) {
                Int64 right = (Int64)frame.Pop();
                frame.Push(((Int64)frame.Pop()) > right);
                return +1;
            }
        }

        internal sealed class GreaterThanByte : GreaterThanInstruction {
            public override int Run(InterpretedFrame frame) {
                Byte right = (Byte)frame.Pop();
                frame.Push(((Byte)frame.Pop()) > right);
                return +1;
            }
        }

        internal sealed class GreaterThanUInt16 : GreaterThanInstruction {
            public override int Run(InterpretedFrame frame) {
                UInt16 right = (UInt16)frame.Pop();
                frame.Push(((UInt16)frame.Pop()) > right);
                return +1;
            }
        }

        internal sealed class GreaterThanUInt32 : GreaterThanInstruction {
            public override int Run(InterpretedFrame frame) {
                UInt32 right = (UInt32)frame.Pop();
                frame.Push(((UInt32)frame.Pop()) > right);
                return +1;
            }
        }

        internal sealed class GreaterThanUInt64 : GreaterThanInstruction {
            public override int Run(InterpretedFrame frame) {
                UInt64 right = (UInt64)frame.Pop();
                frame.Push(((UInt64)frame.Pop()) > right);
                return +1;
            }
        }

        internal sealed class GreaterThanSingle : GreaterThanInstruction {
            public override int Run(InterpretedFrame frame) {
                Single right = (Single)frame.Pop();
                frame.Push(((Single)frame.Pop()) > right);
                return +1;
            }
        }

        internal sealed class GreaterThanDouble : GreaterThanInstruction {
            public override int Run(InterpretedFrame frame) {
                Double right = (Double)frame.Pop();
                frame.Push(((Double)frame.Pop()) > right);
                return +1;
            }
        }

        public static Instruction Create(Type type) {
            Debug.Assert(!type.IsEnum());
            switch (type.GetTypeCode()) {
                case TypeCode.SByte: return _SByte ?? (_SByte = new GreaterThanSByte());
                case TypeCode.Byte: return _Byte ?? (_Byte = new GreaterThanByte());
                case TypeCode.Char: return _Char ?? (_Char = new GreaterThanChar());
                case TypeCode.Int16: return _Int16 ?? (_Int16 = new GreaterThanInt16());
                case TypeCode.Int32: return _Int32 ?? (_Int32 = new GreaterThanInt32());
                case TypeCode.Int64: return _Int64 ?? (_Int64 = new GreaterThanInt64());
                case TypeCode.UInt16: return _UInt16 ?? (_UInt16 = new GreaterThanUInt16());
                case TypeCode.UInt32: return _UInt32 ?? (_UInt32 = new GreaterThanUInt32());
                case TypeCode.UInt64: return _UInt64 ?? (_UInt64 = new GreaterThanUInt64());
                case TypeCode.Single: return _Single ?? (_Single = new GreaterThanSingle());
                case TypeCode.Double: return _Double ?? (_Double = new GreaterThanDouble());

                default:
                    throw Assert.Unreachable;
            }
        }

        public override string ToString() {
            return "GreaterThan()";
        }
    }
}


text:
namespace midi {

// This class enumerates UsbMidiDevices.
class USB_MIDI_EXPORT UsbMidiDeviceFactoryAndroid
      : public UsbMidiDevice::Factory {
 public:
  UsbMidiDeviceFactoryAndroid();

  UsbMidiDeviceFactoryAndroid(const UsbMidiDeviceFactoryAndroid&) = delete;
  UsbMidiDeviceFactoryAndroid& operator=(const UsbMidiDeviceFactoryAndroid&) =
      delete;

  ~UsbMidiDeviceFactoryAndroid() override;

  // UsbMidiDevice::Factory implementation.
  void EnumerateDevices(UsbMidiDeviceDelegate* delegate,
                        Callback callback) override;

  void OnUsbMidiDeviceRequestDone(
      JNIEnv* env,
      const base::android::JavaParamRef<jobjectArray>& devices);
  void OnUsbMidiDeviceAttached(
      JNIEnv* env,
      const base::android::JavaParamRef<jobject>& device);
  void OnUsbMidiDeviceDetached(
      JNIEnv* env,
      jint index);

 private:
  base::android::ScopedJavaGlobalRef<jobject> raw_factory_;
  // Not owned.
  UsbMidiDeviceDelegate* delegate_;
  Callback callback_;
};

}  // namespace midi

#endif  // MEDIA_MIDI_USB_MIDI_DEVICE_FACTORY_ANDROID_H_


text:
using System;
using System.Collections.Generic;
using System.Linq;

namespace osuElements.Replays
{
    public class KeyPress : IComparable<KeyPress>
    {
        public List<ReplayFrame> Frames { get; }

        public KeyPress(IEnumerable<ReplayFrame> frames, int nexttime, ReplayKeys keys) {
            var replayFrames = frames?.ToList() ?? new List<ReplayFrame>();
            Frames = replayFrames;

            Start = replayFrames.Count > 0 ? replayFrames.Min(f => f.Time) : 0;
            if (replayFrames.Count > 0)
                Position = new Position(replayFrames[0].X, replayFrames[0].Y);
            End = nexttime;
            ReplayKeys = keys;
        }
        public int Start { get; set; }
        public int End { get; set; }
        public ReplayKeys ReplayKeys { get; set; }
        public int Timing { get; set; }
        public Position Position { get; set; }
        public int CompareTo(KeyPress other) {
            return Start.CompareTo(other.Start);
        }

        public override string ToString() {
            return $"{Start} - {End} : {Timing}";
        }
    }
}


text:
@interface GrowlSpeechPrefs : NSPreferencePane {
	IBOutlet NSTableView	*voiceList;
	NSArray					*voices;
	NSSpeechSynthesizer		*lastPreview;
}
- (IBAction) previewVoice:(id)sender;
- (IBAction) voiceClicked:(id)sender;

@property (nonatomic, retain) NSArray *voices;

@end


text:
if grep "NotebookApp.password" ~/.jupyter/jupyter_notebook_config.py ; then

	# http://ramhiser.com/2015/02/01/configuring-ipython-notebook-support-for-pyspark/
	export SPARK_HOME="/opt/spark"
	#export PYSPARK_SUBMIT_ARGS="--master cloudera0.acis.ufl.edu"
	export PYSPARK_SUBMIT_ARGS="--executor-memory 80G --driver-memory 80G --num-executors 3 --executor-cores 5 pyspark-shell "

#--jars ${SPARK_HOME}/jars/elasticsearch-spark_2.11-2.4.0.jar
	jupyter notebook --ip='*' --no-browser

else
	echo "No password"
	echo "See https://jupyter-notebook.readthedocs.io/en/latest/public_server.html#securing-a-notebook-server"
fi


text:
package org.ihtsdo.otf.mapping.mojo;

import org.apache.maven.plugin.MojoExecutionException;
import org.ihtsdo.otf.mapping.jpa.services.MappingServiceJpa;
import org.ihtsdo.otf.mapping.model.MapAdvice;
import org.ihtsdo.otf.mapping.services.MappingService;

/**
 * Removes a map advice entirely from environment
 *
 * See admin/remover/pom.xml for a sample execution.
 *
 * @goal remove-map-advice
 * @phase package
 */
public class MapAdviceRemoverMojo extends AbstractOtfMappingMojo {

  /**
   * The refSet id
   * @parameter refsetId
   */
  private String mapAdviceName = null;

  /**
   * Executes the plugin.
   *
   * @throws MojoExecutionException the mojo execution exception
   */
  @Override
  public void execute() throws MojoExecutionException {
    getLog().info("Removing map advice");
    getLog().info("  mapAdviceName = " + mapAdviceName);

    setupBindInfoPackage();

    if (mapAdviceName == null) {
      throw new MojoExecutionException(
          "You must specify the full name of the map advice.");
    }

    try (final MappingService mappingService = new MappingServiceJpa();) {

      MapAdvice mapAdvice = null;
      for (MapAdvice ma : mappingService.getMapAdvices().getIterable()) {
        if (ma.getName().equals(mapAdviceName))
          mapAdvice = ma;
      }
      if (mapAdvice == null)
        throw new MojoExecutionException(
            "The map advice to be removed does not exist");

      getLog()
          .info("Found map advice to remove (id = " + mapAdvice.getId() + ")");

      // Remove the advice
      mappingService.removeMapAdviceFromEnvironment(mapAdvice);

      getLog().info("Done ...");
    } catch (Exception e) {
      e.printStackTrace();
      throw new MojoExecutionException(
          "Removing map advice from environment failed.", e);
    }

  }
}


text:
import cgi
import re
import os
import functools
import time
from webob import Response

import keystone.logic.types.fault as fault

TEMPLATES = {}
DEBUG = False
TEMPLATE_PATH = ['./', './views/']

class BaseTemplate(object):
    """ Base class and minimal API for template adapters """
    extentions = ['tpl', 'html', 'thtml', 'stpl']
    settings = {}  #used in prepare()
    defaults = {}  #used in render()

    def __init__(self, source=None, name=None, lookup=[], encoding='utf8',
                 **settings):
        """ Create a new template.
        If the source parameter (str or buffer) is missing, the name argument
        is used to guess a template filename. Subclasses can assume that
        self.source and/or self.filename are set. Both are strings.
        The lookup, encoding and settings parameters are stored as instance
        variables.
        The lookup parameter stores a list containing directory paths.
        The encoding parameter should be used to decode byte strings or files.
        The settings parameter contains a dict for engine-specific settings.
        """
        self.name = name
        self.source = source.read() if hasattr(source, 'read') else source
        self.filename = source.filename if hasattr(source, 'filename') else None
        self.lookup = map(os.path.abspath, lookup)
        self.encoding = encoding
        self.settings = self.settings.copy() # Copy from class variable
        self.settings.update(settings) # Apply
        if not self.source and self.name:
            self.filename = self.search(self.name, self.lookup)
            if not self.filename:
                raise TemplateError('Template %s not found.' % repr(name))
        if not self.source and not self.filename:
            raise TemplateError('No template specified.')
        self.prepare(**self.settings)

    @classmethod
    def search(cls, name, lookup=[]):
        """ Search name in all directories specified in lookup.
        First without, then with common extensions. Return first hit. """
        if os.path.isfile(name):
            return name
        for spath in lookup:
            fname = os.path.join(spath, name)
            if os.path.isfile(fname):
                return fname
            for ext in cls.extentions:
                if os.path.isfile('%s.%s' % (fname, ext)):
                    return '%s.%s' % (fname, ext)

    @classmethod
    def global_config(cls, key, *args):
        ''' This reads or sets the global settings stored in class.settings. '''
        if args:
            cls.settings[key] = args[0]
        else:
            return cls.settings[key]

    def prepare(self, **options):
        """ Run preparations (parsing, caching, ...).
        It should be possible to call this again to refresh a template or to
        update settings.
        """
        raise NotImplementedError

    def render(self, **args):
        """ Render the template with the specified local variables and return
        a single byte or unicode string. If it is a byte string, the encoding
        must match self.encoding. This method must be thread-safe!
        """
        raise NotImplementedError

class SimpleTemplate(BaseTemplate):
    blocks = ('if','elif','else','try','except','finally','for','while','with','def','class')
    dedent_blocks = ('elif', 'else', 'except', 'finally')

    def prepare(self, escape_func=cgi.escape, noescape=False):
        self.cache = {}
        if self.source:
            self.code = self.translate(self.source)
            self.co = compile(self.code, '<string>', 'exec')
        else:
            self.code = self.translate(open(self.filename).read())
            self.co = compile(self.code, self.filename, 'exec')
        enc = self.encoding
        touni = functools.partial(unicode, encoding=self.encoding)
        self._str = lambda x: touni(x, enc)
        self._escape = lambda x: escape_func(touni(x))
        if noescape:
            self._str, self._escape = self._escape, self._str

    def translate(self, template):
        stack = [] # Current Code indentation
        lineno = 0 # Current line of code
        ptrbuffer = [] # Buffer for printable strings and token tuple instances
        codebuffer = [] # Buffer for generated python code
        touni = functools.partial(unicode, encoding=self.encoding)
        multiline = dedent = False

        def yield_tokens(line):
            for i, part in enumerate(re.split(r'\{\{(.*?)\}\}', line)):
                if i % 2:
                    if part.startswith('!'): yield 'RAW', part[1:]
                    else: yield 'CMD', part
                else: yield 'TXT', part

        def split_comment(codeline):
            """ Removes comments from a line of code. """
            line = codeline.splitlines()[0]
            try:
                tokens = list(tokenize.generate_tokens(iter(line).next))
            except tokenize.TokenError:
                return line.rsplit('#',1) if '#' in line else (line, '')
            for token in tokens:
                if token[0] == tokenize.COMMENT:
                    start, end = token[2][1], token[3][1]
                    return codeline[:start] + codeline[end:], codeline[start:end]
            return line, ''

        def flush(): # Flush the ptrbuffer
            if not ptrbuffer: return
            cline = ''
            for line in ptrbuffer:
                for token, value in line:
                    if token == 'TXT':
                        cline += repr(value)
                    elif token == 'RAW':
                        cline += '_str(%s)' % value
                    elif token == 'CMD':
                        cline += '_escape(%s)' % value
                    cline +=  ', '
                cline = cline[:-2] + '\\\n'
            cline = cline[:-2]
            if cline[:-1].endswith('\\\\\\\\\\n'):
                cline = cline[:-7] + cline[-1] # 'nobr\\\\\n' --> 'nobr'
            cline = '_printlist([' + cline + '])'
            del ptrbuffer[:] # Do this before calling code() again
            code(cline)

        def code(stmt):
            for line in stmt.splitlines():
                codebuffer.append('  ' * len(stack) + line.strip())

        for line in template.splitlines(True):
            lineno += 1
            line = line if isinstance(line, unicode)\
                        else unicode(line, encoding=self.encoding)
            if lineno <= 2:
                m = re.search(r"%.*coding[:=]\s*([-\w\.]+)", line)
                if m: self.encoding = m.group(1)
                if m: line = line.replace('coding','coding (removed)')
            if line.strip()[:2].count('%') == 1:
                line = line.split('%',1)[1].lstrip() # Full line following the %
                cline = split_comment(line)[0].strip()
                cmd = re.split(r'[^a-zA-Z0-9_]', cline)[0]
                flush() ##encodig (TODO: why?)
                if cmd in self.blocks or multiline:
                    cmd = multiline or cmd
                    dedent = cmd in self.dedent_blocks # "else:"
                    if dedent and not oneline and not multiline:
                        cmd = stack.pop()
                    code(line)
                    oneline = not cline.endswith(':') # "if 1: pass"
                    multiline = cmd if cline.endswith('\\') else False
                    if not oneline and not multiline:
                        stack.append(cmd)
                elif cmd == 'end' and stack:
                    code('#end(%s) %s' % (stack.pop(), line.strip()[3:]))
                elif cmd == 'include':
                    p = cline.split(None, 2)[1:]
                    if len(p) == 2:
                        code("_=_include(%s, _stdout, %s)" % (repr(p[0]), p[1]))
                    elif p:
                        code("_=_include(%s, _stdout)" % repr(p[0]))
                    else: # Empty %include -> reverse of %rebase
                        code("_printlist(_base)")
                elif cmd == 'rebase':
                    p = cline.split(None, 2)[1:]
                    if len(p) == 2:
                        code("globals()['_rebase']=(%s, dict(%s))" % (repr(p[0]), p[1]))
                    elif p:
                        code("globals()['_rebase']=(%s, {})" % repr(p[0]))
                else:
                    code(line)
            else: # Line starting with text (not '%') or '%%' (escaped)
                if line.strip().startswith('%%'):
                    line = line.replace('%%', '%', 1)
                ptrbuffer.append(yield_tokens(line))
        flush()
        return '\n'.join(codebuffer) + '\n'

    def subtemplate(self, _name, _stdout, **args):
        if _name not in self.cache:
            self.cache[_name] = self.__class__(name=_name, lookup=self.lookup)
        return self.cache[_name].execute(_stdout, **args)

    def execute(self, _stdout, **args):
        env = self.defaults.copy()
        env.update({'_stdout': _stdout, '_printlist': _stdout.extend,
               '_include': self.subtemplate, '_str': self._str,
               '_escape': self._escape})
        env.update(args)
        eval(self.co, env)
        if '_rebase' in env:
            subtpl, rargs = env['_rebase']
            subtpl = self.__class__(name=subtpl, lookup=self.lookup)
            rargs['_base'] = _stdout[:] #copy stdout
            del _stdout[:] # clear stdout
            return subtpl.execute(_stdout, **rargs)
        return env

    def render(self, **args):
        """ Render the template using keyword arguments as local variables. """
        stdout = []
        self.execute(stdout, **args)
        return ''.join(stdout)

def static_file(resp, req, filename, root, guessmime=True, mimetype=None, download=False):
    """ Opens a file in a safe way and returns a HTTPError object with status
        code 200, 305, 401 or 404. Sets Content-Type, Content-Length and
        Last-Modified header. Obeys If-Modified-Since header and HEAD requests.
    """
    root = os.path.abspath(root) + os.sep
    filename = os.path.abspath(os.path.join(root, filename.strip('/\\')))
    header = {}
    if not filename.startswith(root):
        #return HTTPError(403, "Access denied.")
        return ForbiddenFault("Access denied.")
    if not os.path.exists(filename) or not os.path.isfile(filename):
        #return HTTPError(404, "File does not exist.")
        return fault.ItemNotFoundFault("File does not exist.")
    if not os.access(filename, os.R_OK):
        #return HTTPError(403, "You do not have permission to access this file.")
        return ForbiddenFault("You do not have permission to access this file.")

    if not mimetype and guessmime:
        resp.content_type = mimetypes.guess_type(filename)[0]
    else:
        resp.content_type = mimetype if mimetype else 'text/plain'

    if download == True:
        download = os.path.basename(filename)
    if download:
        resp.content_disposition = 'attachment; filename="%s"' % download

    stats = os.stat(filename)
    lm = time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(stats.st_mtime))
    resp.last_modified = lm
    ims = req.environ.get('HTTP_IF_MODIFIED_SINCE')
    if ims:
        ims = ims.split(";")[0].strip() # IE sends "<date>; length=146"
        ims = parse_date(ims)
        if ims is not None and ims >= int(stats.st_mtime):
            resp.date = time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime())
            return Response(body=None, status=304, headerlist=resp.headerlist)
    resp.content_length = stats.st_size
    if req.method == 'HEAD':
        return Response(body=None, status=200, headerlist=resp.headerlist)
    else:
        return Response(body=open(filename).read(), status=200, headerlist=resp.headerlist)

def template(tpl, template_adapter=SimpleTemplate, **kwargs):
    '''
    Get a rendered template as a string iterator.
    You can use a name, a filename or a template string as first parameter.
    '''
    if tpl not in TEMPLATES or DEBUG:
        settings = kwargs.get('template_settings',{})
        lookup = kwargs.get('template_lookup', TEMPLATE_PATH)
        if isinstance(tpl, template_adapter):
            TEMPLATES[tpl] = tpl
            if settings: TEMPLATES[tpl].prepare(**settings)
        elif "\n" in tpl or "{" in tpl or "%" in tpl or '$' in tpl:
            TEMPLATES[tpl] = template_adapter(source=tpl, lookup=lookup, **settings)
        else:
            TEMPLATES[tpl] = template_adapter(name=tpl, lookup=lookup, **settings)
    if not TEMPLATES[tpl]:
        abort(500, 'Template (%s) not found' % tpl)
    return TEMPLATES[tpl].render(**kwargs)


text:
/* eslint-disable */
const path = require("path");
const webpack = require("webpack");
const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
  entry: ["babel-polyfill", "./index"],
  output: {
    path: path.join(__dirname, "dist"),
    filename: "bundle.js",
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './index.html',
      hash: true,
      filename: 'index.html',
      inject: 'body'
    }),
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.DefinePlugin({
      "process.env": {
        NODE_ENV: JSON.stringify("production")
      }
    }),
    new webpack.optimize.UglifyJsPlugin({
      compressor: {
        warnings: false
      }
    })
  ],
  module: {
    loaders: [
      {
        test: /\.md$/,
        loader: "html-loader!markdown-loader?gfm=false"
      },
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        loader: "babel-loader",
        query: {
          presets: ["es2015", "react"]
        }
      },
      {
        test: /\.css$/,
        loader: "style-loader!css-loader"
      },
      {
        test: /\.(png|jpg|gif)$/,
        loader: "url-loader?limit=8192"
      },
      {
        test: /\.svg$/,
        loader: "url?limit=10000&mimetype=image/svg+xml"
      }
    ]
  }
};


text:
package ch.frostnova.user.auth.api.service;

import ch.frostnova.user.auth.api.exception.AuthenticationException;
import ch.frostnova.user.auth.api.model.LoginCredentials;
import ch.frostnova.user.auth.api.model.User;

/**
 * Created by pwalser on 29.01.2017.
 */
public interface AuthService {

    User authenticate(LoginCredentials loginCredentials) throws AuthenticationException;
}


text:
import { TestBed } from '@angular/core/testing';

import { BrowserSupportService } from './browser-support.service';

describe('BrowserSupportService', () => {
    let service: BrowserSupportService;

    beforeEach(() => {
        TestBed.configureTestingModule({});
        service = TestBed.inject(BrowserSupportService);
    });

    it('should be created', () => {
        expect(service).toBeTruthy();
    });
});


text:
lets practice painting eyesight with regular computer, mouse and anaglyph (red and blue) 3d glasses

use: http://bit.ly/redbluepaint

press f11 for full screen.

use mouse to paint

cool things to paing are intersecting lines and intersecting lines of different colors and an interesting figure. all these enable the ye to find and lock on position. to challange eyes draw (maybe with smaller size) blue on red or with red on blue
on black background.

for example on black background draw a blue smilely. make it a spider by adding horizontal lines on sides of it. then add two vertical red lines on sides.

mouse wheel to change size of point

* left click to draw blue
* middle button to draw red
* right click to draw black

* press 1 to clear screen blue
* press 2 to clear screen red
* press 3 to clear screen black

makes a lot of challenge on brain of eyes. eyes basically say i feel stupid give me a break but you keep practice.

for more like this search:

* dichoptic training
* dichoptic Tetris

dichoptic eyesight training is the latest research in eyesight.
after first practice of 15 minutes i got an effect of 1 to 2 dioptre eyesight enhancement.
it is said in several places the more training the more the effect. lots of practice makes the effect permanent.

it is possible because eyes if not disease are usually ok
but usually not trained to see well because looking at computer long time.
eyes usually can focus given some time.  eyes are too crossed to the center for long distance and too outwards for short distances. and each eye has its own problems  disassociated with the other eye and for short distance there is one and another beyond your normal focal point.

but eyes blur defocus to connect both eyes images better.
all it needs just show brain good information.
to see the problem simply close one eye and see where you see one image switch eyes and see if you see the image in same place,(you should) if you don't see it means you have some eyes crossing disorder which prevents learnign focus.
you can even train with a finger to see if you see same place picture in both eyes. closing the eyes resets the fusing of two pictures by brain. i cam hypothize that the fution of eyes depend on number brain has to care about because in distance there are more pixels so the more close matching of position is important.

one eyes book said eyes should be relaxed instead of squinting for this to work. tension in muscles bends the picture. i found that i need to control the position of eyes consciously and also this book said need to learn to see with whole eye.
so i found that my eye's shape is to see in center  from eye glasses. sometimes relaxing and seeing with whole eye works. Sometimes it don't. I don't understand it yet.
you shouldn't look through top of the eye rather from center notice this.

anyways matching position requirers practice.


text:
{
  "title": "今井先生のQSS本Rコードがtidyverse化されたものがあるときき、探してみたところすぐに発見し、Bookdownでhtml化した。これ最高やないか。https://t.co/XmBwxTHPc5",
  "date": "2018-08-06"
}

# blogdown

> **Mark Sellors** (@sellorm; 10/3): How the https://t.co/82OUqvFPst website works -> https://t.co/COHRuEZKyy  [↪](https://twitter.com/xieyihui/status/1026116643322310656)

<!-- -->

> **G. Elliott Morris📈🤷♂** (@gelliottmorris; 2/0): @stevenvmiller I use blogdown with a modification of the minimal theme for my personal site, and the highline theme for my blog.  [↪](https://twitter.com/xieyihui/status/1026166286907269120)

<!-- -->

> **Steven V. Miller** (@stevenvmiller; 1/0): @gelliottmorris Likewise using Jekyll with my own Frankenstein of jekyll-new and Favepersonal (https://t.co/Ymhc5r0oA3). I know I should be moving things to blogdown but that'd mean futzing with things; I'm sure.  [↪](https://twitter.com/xieyihui/status/1026167051558236161)

<!-- -->

# bookdown

> **松浦総一 Soichi Matsuura** (@matsuura_rits; 18/10): 今井先生のQSS本Rコードがtidyverse化されたものがあるときき、探してみたところすぐに発見し、Bookdownでhtml化した。これ最高やないか。https://t.co/XmBwxTHPc5  [↪](https://twitter.com/xieyihui/status/1026119494941388801)

<!-- -->

# knitr

> **Stefan Marr** (@smarr; 0/0): @lindsey @tomaspetricek I find notebooks uncomfortable, because they are somewhat restricting me, I feel.
However, RStudio and its Knitr/RMarkdown has turned the idea of notebooks "inside out". The interaction pattern is more comfortable for me. Perhaps also worth a look. It's a different kind of REPL.  [↪](https://twitter.com/xieyihui/status/1026088883916816384)

<!-- -->

# xaringan

> **Thamy💕** (@tamiressilvaa17; 1/0): Toda vez que encontro xaringan ele ta com aquele olho dele igual japones kkkkkkkkkkkkk  [↪](https://twitter.com/xieyihui/status/1026273276761399296)

<!-- -->

> **Ph.Demetri** (@PhDemetri; 1/0): @sharlagelfand The only reason I would like to use beamer is because I already know LaTex.  xaringan looks neat, but dont I need to use CSS to make themes?  [↪](https://twitter.com/xieyihui/status/1026074160672464896)

<!-- -->

> **Sharla Gelfand** (@sharlagelfand; 0/0): @PhDemetri does it need to be beamer? you may want to look into xaringan! https://t.co/VoP4mCsUi1  [↪](https://twitter.com/xieyihui/status/1025948662382448641)

<!-- -->


text:
 Logins

 Online Accounts

 Software Licences

 Internet

 Credit Cards

TOOLS

 Password generator


text: A Windows Phone application that makes bike rides even more fabulous


text:
package kg.apc.emulators;

/**
 *
 * @author undera
 */
public class BinaryTools {

    public static byte[] hexStringToByteArray(String hexEncodedBinary) {
        if (hexEncodedBinary.length() % 2 == 0) {
            char[] sc = hexEncodedBinary.toCharArray();
            byte[] ba = new byte[sc.length / 2];

            for (int i = 0; i < ba.length; i++) {
                int nibble0 = Character.digit(sc[i * 2], 16);
                int nibble1 = Character.digit(sc[i * 2 + 1], 16);
                if (nibble0 == -1 || nibble1 == -1) {
                    throw new IllegalArgumentException(
                            "Hex-encoded binary string contains an invalid hex digit in '" + sc[i * 2] + sc[i * 2 + 1] + "'");
                }
                ba[i] = (byte) ((nibble0 << 4) | (nibble1));
            }

            return ba;
        } else {
            throw new IllegalArgumentException(
                    "Hex-encoded binary string contains an uneven no. of digits");
        }
    }
}


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;
using System.Collections.Immutable;

namespace Microsoft.CodeAnalysis
{
    /// <summary>
    /// Represents a disposable blob of memory accessed via unsafe pointer.
    /// </summary>
    internal abstract class AbstractMemoryBlock : IDisposable
    {
        /// <summary>
        /// Pointer to the underlying data or <see cref="IntPtr.Zero"/> if the data have been disposed.
        /// </summary>
        public abstract IntPtr Pointer
        {
            get;
        }

        public bool IsDisposed
        {
            get { return Pointer == IntPtr.Zero; }
        }

        public abstract int Size
        {
            get;
        }

        /// <summary>
        /// Returns the content of the memory block.
        /// </summary>
        /// <remarks>
        /// Only creates a copy of the data if they are not represented by a managed byte array.
        /// </remarks>
        public abstract ImmutableArray<byte> GetContent();

        protected abstract void Dispose(bool disposing);

        /// <summary>
        /// Disposes the block. The operation is thread-safe and idempotent.
        /// </summary>
        public void Dispose()
        {
            Dispose(disposing: true);
        }

    }
}


text:
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using BulletUnity;

[CustomEditor(typeof(BSliderConstraint))]
public class BSliderConstraintEditor : Editor {

    public override void OnInspectorGUI() {
        BSliderConstraint hc = (BSliderConstraint)target;
        EditorGUILayout.HelpBox(BSliderConstraint.HelpMessage, MessageType.Info);

        BTypedConstraintEditor.DrawTypedConstraint(hc);

        EditorGUILayout.Separator();
        EditorGUILayout.LabelField("Limits", EditorStyles.boldLabel);
        hc.lowerLinearLimit = EditorGUILayout.FloatField("Lower Linear Limit", hc.lowerLinearLimit);
        hc.upperLinearLimit = EditorGUILayout.FloatField("Upper Linear Limit", hc.upperLinearLimit);

        hc.lowerAngularLimitRadians = EditorGUILayout.FloatField("Lower Angular Limit (Deg.)", hc.lowerAngularLimitRadians * Mathf.Rad2Deg) * Mathf.Deg2Rad;
        hc.upperAngularLimitRadians = EditorGUILayout.FloatField("Upper Angular Limit (Deg.)", hc.upperAngularLimitRadians * Mathf.Rad2Deg) * Mathf.Deg2Rad;

        if (GUI.changed)
        {
            serializedObject.ApplyModifiedProperties();
            EditorUtility.SetDirty(hc);
            EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetActiveScene());
            Repaint();
        }
    }
}