text:
/**
 * Autogenerated by Thrift Compiler (0.9.1)
 *
 * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
 *  @generated
 */
package org.apache.hive.service.cli.thrift;

import org.apache.thrift.scheme.IScheme;
import org.apache.thrift.scheme.SchemeFactory;
import org.apache.thrift.scheme.StandardScheme;

import org.apache.thrift.scheme.TupleScheme;
import org.apache.thrift.protocol.TTupleProtocol;
import org.apache.thrift.protocol.TProtocolException;
import org.apache.thrift.EncodingUtils;
import org.apache.thrift.TException;
import org.apache.thrift.async.AsyncMethodCallback;
import org.apache.thrift.server.AbstractNonblockingServer.*;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.EnumMap;
import java.util.Set;
import java.util.HashSet;
import java.util.EnumSet;
import java.util.Collections;
import java.util.BitSet;
import java.nio.ByteBuffer;
import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TArrayTypeEntry implements org.apache.thrift.TBase<TArrayTypeEntry, TArrayTypeEntry._Fields>, java.io.Serializable, Cloneable, Comparable<TArrayTypeEntry> {
  private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("TArrayTypeEntry");

  private static final org.apache.thrift.protocol.TField OBJECT_TYPE_PTR_FIELD_DESC = new org.apache.thrift.protocol.TField("objectTypePtr", org.apache.thrift.protocol.TType.I32, (short)1);

  private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();
  static {
    schemes.put(StandardScheme.class, new TArrayTypeEntryStandardSchemeFactory());
    schemes.put(TupleScheme.class, new TArrayTypeEntryTupleSchemeFactory());
  }

  public int objectTypePtr; // required

  /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
  public enum _Fields implements org.apache.thrift.TFieldIdEnum {
    OBJECT_TYPE_PTR((short)1, "objectTypePtr");

    private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();

    static {
      for (_Fields field : EnumSet.allOf(_Fields.class)) {
        byName.put(field.getFieldName(), field);
      }
    }

    /**
     * Find the _Fields constant that matches fieldId, or null if its not found.
     */
    public static _Fields findByThriftId(int fieldId) {
      switch(fieldId) {
        case 1: // OBJECT_TYPE_PTR
          return OBJECT_TYPE_PTR;
        default:
          return null;
      }
    }

    /**
     * Find the _Fields constant that matches fieldId, throwing an exception
     * if it is not found.
     */
    public static _Fields findByThriftIdOrThrow(int fieldId) {
      _Fields fields = findByThriftId(fieldId);
      if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!");
      return fields;
    }

    /**
     * Find the _Fields constant that matches name, or null if its not found.
     */
    public static _Fields findByName(String name) {
      return byName.get(name);
    }

    private final short _thriftId;
    private final String _fieldName;

    _Fields(short thriftId, String fieldName) {
      _thriftId = thriftId;
      _fieldName = fieldName;
    }

    public short getThriftFieldId() {
      return _thriftId;
    }

    public String getFieldName() {
      return _fieldName;
    }
  }

  // isset id assignments
  private static final int __OBJECTTYPEPTR_ISSET_ID = 0;
  private byte __isset_bitfield = 0;
  public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
  static {
    Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
    tmpMap.put(_Fields.OBJECT_TYPE_PTR, new org.apache.thrift.meta_data.FieldMetaData("objectTypePtr", org.apache.thrift.TFieldRequirementType.REQUIRED,
        new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32        , "TTypeEntryPtr")));
    metaDataMap = Collections.unmodifiableMap(tmpMap);
    org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(TArrayTypeEntry.class, metaDataMap);
  }

  public TArrayTypeEntry() {
  }

  public TArrayTypeEntry(
    int objectTypePtr)
  {
    this();
    this.objectTypePtr = objectTypePtr;
    setObjectTypePtrIsSet(true);
  }

  /**
   * Performs a deep copy on <i>other</i>.
   */
  public TArrayTypeEntry(TArrayTypeEntry other) {
    __isset_bitfield = other.__isset_bitfield;
    this.objectTypePtr = other.objectTypePtr;
  }

  public TArrayTypeEntry deepCopy() {
    return new TArrayTypeEntry(this);
  }

  @Override
  public void clear() {
    setObjectTypePtrIsSet(false);
    this.objectTypePtr = 0;
  }

  public int getObjectTypePtr() {
    return this.objectTypePtr;
  }

  public TArrayTypeEntry setObjectTypePtr(int objectTypePtr) {
    this.objectTypePtr = objectTypePtr;
    setObjectTypePtrIsSet(true);
    return this;
  }

  public void unsetObjectTypePtr() {
    __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __OBJECTTYPEPTR_ISSET_ID);
  }

  /** Returns true if field objectTypePtr is set (has been assigned a value) and false otherwise */
  public boolean isSetObjectTypePtr() {
    return EncodingUtils.testBit(__isset_bitfield, __OBJECTTYPEPTR_ISSET_ID);
  }

  public void setObjectTypePtrIsSet(boolean value) {
    __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __OBJECTTYPEPTR_ISSET_ID, value);
  }

  public void setFieldValue(_Fields field, Object value) {
    switch (field) {
    case OBJECT_TYPE_PTR:
      if (value == null) {
        unsetObjectTypePtr();
      } else {
        setObjectTypePtr((Integer)value);
      }
      break;

    }
  }

  public Object getFieldValue(_Fields field) {
    switch (field) {
    case OBJECT_TYPE_PTR:
      return Integer.valueOf(getObjectTypePtr());

    }
    throw new IllegalStateException();
  }

  /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
  public boolean isSet(_Fields field) {
    if (field == null) {
      throw new IllegalArgumentException();
    }

    switch (field) {
    case OBJECT_TYPE_PTR:
      return isSetObjectTypePtr();
    }
    throw new IllegalStateException();
  }

  @Override
  public boolean equals(Object that) {
    if (that == null)
      return false;
    if (that instanceof TArrayTypeEntry)
      return this.equals((TArrayTypeEntry)that);
    return false;
  }

  public boolean equals(TArrayTypeEntry that) {
    if (that == null)
      return false;

    boolean this_present_objectTypePtr = true;
    boolean that_present_objectTypePtr = true;
    if (this_present_objectTypePtr || that_present_objectTypePtr) {
      if (!(this_present_objectTypePtr && that_present_objectTypePtr))
        return false;
      if (this.objectTypePtr != that.objectTypePtr)
        return false;
    }

    return true;
  }

  @Override
  public int hashCode() {
    return 0;
  }

  @Override
  public int compareTo(TArrayTypeEntry other) {
    if (!getClass().equals(other.getClass())) {
      return getClass().getName().compareTo(other.getClass().getName());
    }

    int lastComparison = 0;

    lastComparison = Boolean.valueOf(isSetObjectTypePtr()).compareTo(other.isSetObjectTypePtr());
    if (lastComparison != 0) {
      return lastComparison;
    }
    if (isSetObjectTypePtr()) {
      lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.objectTypePtr, other.objectTypePtr);
      if (lastComparison != 0) {
        return lastComparison;
      }
    }
    return 0;
  }

  public _Fields fieldForId(int fieldId) {
    return _Fields.findByThriftId(fieldId);
  }

  public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
    schemes.get(iprot.getScheme()).getScheme().read(iprot, this);
  }

  public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
    schemes.get(oprot.getScheme()).getScheme().write(oprot, this);
  }

  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder("TArrayTypeEntry(");
    boolean first = true;

    sb.append("objectTypePtr:");
    sb.append(this.objectTypePtr);
    first = false;
    sb.append(")");
    return sb.toString();
  }

  public void validate() throws org.apache.thrift.TException {
    // check for required fields
    // alas, we cannot check 'objectTypePtr' because it's a primitive and you chose the non-beans generator.
    // check for sub-struct validity
  }

  private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
    try {
      write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
    } catch (org.apache.thrift.TException te) {
      throw new java.io.IOException(te);
    }
  }

  private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {
    try {
      // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor.
      __isset_bitfield = 0;
      read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
    } catch (org.apache.thrift.TException te) {
      throw new java.io.IOException(te);
    }
  }

  private static class TArrayTypeEntryStandardSchemeFactory implements SchemeFactory {
    public TArrayTypeEntryStandardScheme getScheme() {
      return new TArrayTypeEntryStandardScheme();
    }
  }

  private static class TArrayTypeEntryStandardScheme extends StandardScheme<TArrayTypeEntry> {

    public void read(org.apache.thrift.protocol.TProtocol iprot, TArrayTypeEntry struct) throws org.apache.thrift.TException {
      org.apache.thrift.protocol.TField schemeField;
      iprot.readStructBegin();
      while (true)
      {
        schemeField = iprot.readFieldBegin();
        if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
          break;
        }
        switch (schemeField.id) {
          case 1: // OBJECT_TYPE_PTR
            if (schemeField.type == org.apache.thrift.protocol.TType.I32) {
              struct.objectTypePtr = iprot.readI32();
              struct.setObjectTypePtrIsSet(true);
            } else {
              org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
            }
            break;
          default:
            org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
        }
        iprot.readFieldEnd();
      }
      iprot.readStructEnd();

      // check for required fields of primitive type, which can't be checked in the validate method
      if (!struct.isSetObjectTypePtr()) {
        throw new org.apache.thrift.protocol.TProtocolException("Required field 'objectTypePtr' was not found in serialized data! Struct: " + toString());
      }
      struct.validate();
    }

    public void write(org.apache.thrift.protocol.TProtocol oprot, TArrayTypeEntry struct) throws org.apache.thrift.TException {
      struct.validate();

      oprot.writeStructBegin(STRUCT_DESC);
      oprot.writeFieldBegin(OBJECT_TYPE_PTR_FIELD_DESC);
      oprot.writeI32(struct.objectTypePtr);
      oprot.writeFieldEnd();
      oprot.writeFieldStop();
      oprot.writeStructEnd();
    }

  }

  private static class TArrayTypeEntryTupleSchemeFactory implements SchemeFactory {
    public TArrayTypeEntryTupleScheme getScheme() {
      return new TArrayTypeEntryTupleScheme();
    }
  }

  private static class TArrayTypeEntryTupleScheme extends TupleScheme<TArrayTypeEntry> {

    @Override
    public void write(org.apache.thrift.protocol.TProtocol prot, TArrayTypeEntry struct) throws org.apache.thrift.TException {
      TTupleProtocol oprot = (TTupleProtocol) prot;
      oprot.writeI32(struct.objectTypePtr);
    }

    @Override
    public void read(org.apache.thrift.protocol.TProtocol prot, TArrayTypeEntry struct) throws org.apache.thrift.TException {
      TTupleProtocol iprot = (TTupleProtocol) prot;
      struct.objectTypePtr = iprot.readI32();
      struct.setObjectTypePtrIsSet(true);
    }
  }

}


text:
import { Meteor } from 'meteor/meteor';
import { RocketChat } from 'meteor/rocketchat:lib';

Meteor.methods({
	'authorization:removeRoleFromPermission'(permission, role) {
		if (!Meteor.userId() || !RocketChat.authz.hasPermission(Meteor.userId(), 'access-permissions')) {
			throw new Meteor.Error('error-action-not-allowed', 'Accessing permissions is not allowed', {
				method: 'authorization:removeRoleFromPermission',
				action: 'Accessing_permissions',
			});
		}

		return RocketChat.models.Permissions.removeRole(permission, role);
	},
});

redpajama_set_name: RedPajamaGithub


text: DOGGIE_DAYCARE.Abby = true;


text:
layout: page
title: Gallagher Angel Air Trade Fair
date: 2016-05-24
author: Martha Myers
tags: weekly links, java
status: published
summary: Nam rhoncus mi at nibh.
banner: images/banner/meeting-01.jpg
booking:
  startDate: 10/02/2019
  endDate: 10/04/2019
  ctyhocn: FYVSSHX
  groupCode: GAATF
published: true
---
Phasellus erat velit, vestibulum et fermentum sit amet, dictum ut enim. Suspendisse suscipit eget diam non tincidunt. Mauris at nisl blandit, eleifend metus nec, pellentesque dolor. Vestibulum neque enim, posuere nec lorem at, placerat consectetur sem. Duis egestas, purus non aliquet sagittis, odio magna iaculis nulla, quis fermentum ipsum ligula id purus. Nam eget risus ut mauris tempus sagittis sed quis libero. Aliquam at consequat erat.

* Ut tincidunt diam nec interdum finibus.

Nulla erat mi, congue et ante non, congue fringilla leo. Vivamus sit amet justo odio. Nulla facilisi. Morbi eget commodo justo. Maecenas rhoncus hendrerit tortor sit amet tempus. In lacinia sem ut velit aliquet, vel posuere enim cursus. Quisque mattis sagittis cursus.
Donec efficitur, ipsum sit amet tincidunt luctus, massa purus lacinia justo, ut blandit velit velit at ipsum. Etiam pellentesque urna nisl. Nam sed turpis purus. Quisque imperdiet purus id pharetra fringilla. Aliquam vitae auctor leo. Curabitur erat ante, pretium nec orci a, efficitur semper ex. Aenean sit amet sapien pharetra orci vulputate dignissim dictum vel nunc. Quisque risus nulla, dictum et turpis at, condimentum facilisis nisl. Phasellus elit nisl, auctor vel iaculis id, pellentesque a lacus. Curabitur pulvinar ipsum nec arcu fringilla, et consequat nibh porttitor. Quisque lacus metus, dignissim et dolor non, malesuada egestas diam.


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
Uses of Class org.jbox2d.dynamics.joints.LimitState
</TITLE>

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Class
org.jbox2d.dynamics.joints.LimitState

Packages that use LimitState

org.jbox2d.dynamics.joints
This package deals with all things joint-related.

Uses of LimitState in org.jbox2d.dynamics.joints

Fields in org.jbox2d.dynamics.joints declared as LimitState

 LimitState
RevoluteJoint.m_limitState

 LimitState
PrismaticJoint.m_limitState

 LimitState
PulleyJoint.m_limitState1

 LimitState
PulleyJoint.m_limitState2

 LimitState
PulleyJoint.m_state

Methods in org.jbox2d.dynamics.joints that return LimitState

static LimitState
LimitState.valueOf(java.lang.String name)

          Returns the enum constant of this type with the specified name.

static LimitState[]
LimitState.values()

          Returns an array containing the constants of this enum type, in
the order they're declared.

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes


text:
package nachos.vm;

import nachos.machine.*;
import nachos.threads.*;
import nachos.userprog.*;
import nachos.vm.*;

/**
 * A <tt>UserProcess</tt> that supports demand-paging.
 */
public class VMProcess extends UserProcess {
    /**
     * Allocate a new process.
     */
    public VMProcess() {
        super();
    }

    /**
     * Save the state of this process in preparation for a context switch.
     * Called by <tt>UThread.saveState()</tt>.
     */
    public void saveState() {
        super.saveState();
    }

    /**
     * Restore the state of this process after a context switch. Called by
     * <tt>UThread.restoreState()</tt>.
     */
    public void restoreState() {
        super.restoreState();
    }

    /**
     * Initializes page tables for this process so that the executable can be
     * demand-paged.
     *
     * @return	<tt>true</tt> if successful.
     */
    protected boolean loadSections() {
        return super.loadSections();
    }

    /**
     * Release any resources allocated by <tt>loadSections()</tt>.
     */
    protected void unloadSections() {
        super.unloadSections();
    }

    /**
     * Handle a user exception. Called by
     * <tt>UserKernel.exceptionHandler()</tt>. The
     * <i>cause</i> argument identifies which exception occurred; see the
     * <tt>Processor.exceptionZZZ</tt> constants.
     *
     * @param	cause	the user exception that occurred.
     */
    public void handleException(int cause) {
        Processor processor = Machine.processor();

        switch (cause) {
        default:
            super.handleException(cause);
            break;
        }
    }

    private static final int pageSize = Processor.pageSize;
    private static final char dbgProcess = 'a';
    private static final char dbgVM = 'v';
}


text:
var path = require("path");
var fs = require("fs");
var OS = require("os");
var prependFile = require('prepend-file');
var CopyWebpackPlugin = require('copy-webpack-plugin');
var CleanWebpackPlugin = require('clean-webpack-plugin');
var webpack = require('webpack');
var pkg = require("./package.json");

var outputDir = path.join(__dirname, "build");
var outputFilename = 'cli.bundled.js';

module.exports = {
  entry: {
    cli: path.join(__dirname, "node_modules", "truffle-core", "cli.js"),
    chain: path.join(__dirname, "node_modules", "truffle-core", "chain.js")
  },
  target: 'node',
  node: {
    // For this option, see here: https://github.com/webpack/webpack/issues/1599
    __dirname: false,
    __filename: false
  },
  output: {
    path: outputDir,
    filename: '[name].bundled.js'
  },
  devtool: 'source-map',
  module: {
    rules: [
      { test: /\.js$/, use: "shebang-loader" }
    ]
  },
  externals: [
    // If you look at webpack's docs, `externals` doesn't need to be a function.
    // But I never got it to work otherwise, so this is a function because "it works".
    function(context, request, callback) {

      // truffle-config uses the original-require module.
      // Here, we leave it as an external, and use the original-require
      // module that's a dependency of Truffle instead.
      if (/^original-require$/.test(request)) {
        return callback(null, 'commonjs original-require');
      }

      // We want to leave solc as an eternal dependency as well (for now)
      if (/^solc$/.test(request)) {
        return callback(null, 'commonjs solc');
      }

      // Mocha doesn't seem to bundle well either. This is a stop-gap until
      // I can look into it further.
      if (/^mocha$/.test(request)) {
        return callback(null, 'commonjs mocha');
      }

      callback();
    }
  ],
  plugins: [
    new webpack.DefinePlugin({
      "BUNDLE_VERSION": JSON.stringify(pkg.version),
      "BUNDLE_CHAIN_FILENAME": JSON.stringify("chain.bundled.js")
    }),

    // Put the shebang back on.
    new webpack.BannerPlugin({banner: '#!/usr/bin/env node\n', raw: true}),

    // `truffle test`
    new CopyWebpackPlugin([
      { from: path.join(__dirname, "node_modules", "truffle-core", "lib", "testing", "Assert.sol") },
      { from: path.join(__dirname, "node_modules", "truffle-core", "lib", "testing", "SafeSend.sol") },
      {
        from: path.join(__dirname, "node_modules", "truffle-core", "lib", "templates/"),
        to: "templates",
        flatten: true
      },
    ]),

    new CleanWebpackPlugin(["build"]),
  ],
  resolve: {
    alias: {
      // fsevents is used by chokidar and is an optional requirement
      // It doesn't pack well, and is OS X specific, so let's get rid of it.
      "fsevents": path.join(__dirname, "./nil.js"),
      "ws": path.join(__dirname, "./nil.js"),
      "scrypt": "js-scrypt",
      "secp256k1": path.join(__dirname, "node_modules", "secp256k1", "elliptic.js")
    }
  }
}


text:
package main

import (
	"fmt"
	"github.com/yahoo/athenz/provider/azure/sia-vm"
	"github.com/yahoo/athenz/provider/azure/sia-vm/data/attestation"
	"github.com/yahoo/athenz/provider/azure/sia-vm/logutil"
	"github.com/yahoo/athenz/provider/azure/sia-vm/options"
	"github.com/yahoo/athenz/provider/azure/sia-vm/util"
	"io"
	"io/ioutil"
	"log"
	"log/syslog"
	"os"
	"time"

	"flag"
	"os/signal"
	"syscall"
)

var MetaEndPoint = "http://169.254.169.254"
var ApiVersion = "2020-06-01"

const siaMainDir = "/var/lib/sia"
const siaLinkDir = "/var/run/sia"
const siaVersion = "1.0"

func main() {
	cmd := flag.String("cmd", "", "optional sub command to run")
	metaEndPoint := flag.String("meta", "", "optional meta endpoint to use for debugging")
	ztsEndPoint := flag.String("zts", "", "optional zts endpoint")
	ztsServerName := flag.String("ztsservername", "", "zts server name for tls connections")
	ztsCACert := flag.String("ztscacert", "", "zts CA certificate file")
	ztsAzureDomain := flag.String("ztsazuredomain", "", "ZTS Azure Domain")
	ztsResourceUri := flag.String("ztsresourceuri", "", "ZTS AD App Resource URI")
	azureProvider := flag.String("azureProvider", "", "Azure Provider Service Name")
	countryName := flag.String("countryname", "US", "X.509 Certificate Country Value")
	pConf := flag.String("config", "/etc/sia/sia_config", "The config file to run against")
	noSysLog := flag.Bool("nosyslog", false, "turn off syslog, log to stdout")

	flag.Parse()

	var sysLogger io.Writer
	if *noSysLog {
		sysLogger = os.Stdout
	} else {
		var err error
		sysLogger, err = syslog.New(syslog.LOG_INFO|syslog.LOG_DAEMON, "siad")
		if err != nil {
			log.Printf("Unable to create sys logger: %v\n", err)
			sysLogger = os.Stdout
		}
	}

	if *ztsEndPoint == "" {
		logutil.LogFatal(sysLogger, "ztsEndPoint argument must be specified\n")
	}
	if *ztsAzureDomain == "" {
		logutil.LogFatal(sysLogger, "ztsazuredomain argument must be specified\n")
	}
	if *ztsResourceUri == "" {
		logutil.LogFatal(sysLogger, "ztsresourceuri argument must be specified\n")
	}
	if *metaEndPoint != "" {
		MetaEndPoint = *metaEndPoint
	}

	identityDocument, err := attestation.GetIdentityDocument(MetaEndPoint, ApiVersion, sysLogger)
	if err != nil {
		logutil.LogFatal(sysLogger, "Unable to get the instance identity document, error: %v\n", err)
	}

	confBytes, _ := ioutil.ReadFile(*pConf)
	opts, err := options.NewOptions(confBytes, identityDocument, siaMainDir, siaVersion, *ztsCACert, *ztsServerName, *ztsAzureDomain, *countryName, *azureProvider, sysLogger)
	if err != nil {
		logutil.LogFatal(sysLogger, "Unable to formulate options, error: %v\n", err)
	}

	logutil.LogInfo(sysLogger, "options: %+v\n", opts)

	data, err := getAttestationData(*ztsResourceUri, identityDocument, opts, sysLogger)
	if err != nil {
		logutil.LogFatal(sysLogger, "Unable to formulate attestation data, error: %v\n", err)
	}

	// for now we're going to rotate once every day
	// since our server and role certs are valid for
	// 30 days by default
	rotationInterval := 24 * 60 * time.Minute

	ztsUrl := fmt.Sprintf("https://%s:4443/zts/v1", *ztsEndPoint)

	err = util.SetupSIADirs(siaMainDir, siaLinkDir, sysLogger)
	if err != nil {
		logutil.LogFatal(sysLogger, "Unable to setup sia directories, error: %v\n", err)
	}

	logutil.LogInfo(sysLogger, "Request SSH Certificates: %t\n", opts.Ssh)

	svcs := options.GetSvcNames(opts.Services)

	switch *cmd {
	case "rolecert":
		sia.GetRoleCertificate(ztsUrl,
			fmt.Sprintf("%s/%s.%s.key.pem", opts.KeyDir, opts.Domain, opts.Services[0].Name),
			fmt.Sprintf("%s/%s.%s.cert.pem", opts.CertDir, opts.Domain, opts.Services[0].Name),
			opts,
			sysLogger,
		)
	case "post":
		err := sia.RegisterInstance(data, ztsUrl, identityDocument, opts, sysLogger)
		if err != nil {
			logutil.LogFatal(sysLogger, "Register identity failed, err: %v\n", err)
		}
		logutil.LogInfo(sysLogger, "identity registered for services: %s\n", svcs)
	case "rotate":
		err = sia.RefreshInstance(data, ztsUrl, identityDocument, opts, sysLogger)
		if err != nil {
			logutil.LogFatal(sysLogger, "Refresh identity failed, err: %v\n", err)
		}
		logutil.LogInfo(sysLogger, "Identity successfully refreshed for services: %s\n", svcs)
	default:
		// if we already have a cert file then we're not going to
		// prove our identity since most likely it will not succeed
		// due to boot time check (this could be just a regular
		// service restart for any reason). Instead, we'll just skip
		// over and try to rotate the certs

		initialSetup := true
		if files, err := ioutil.ReadDir(opts.CertDir); err != nil || len(files) <= 0 {
			err := sia.RegisterInstance(data, ztsUrl, identityDocument, opts, sysLogger)
			if err != nil {
				logutil.LogFatal(sysLogger, "Register identity failed, error: %v\n", err)
			}
		} else {
			initialSetup = false
			logutil.LogInfo(sysLogger, "Identity certificate file already exists. Retrieving identity details...\n")
		}
		logutil.LogInfo(sysLogger, "Identity established for services: %s\n", svcs)

		stop := make(chan bool, 1)
		errors := make(chan error, 1)

		go func() {
			for {
				logutil.LogInfo(sysLogger, "Identity being used: %s\n", opts.Name)

				// if we just did our initial setup there is no point
				// to refresh the certs again. so we are going to skip
				// this time around and refresh certs next time

				if !initialSetup {
					data, err := getAttestationData(*ztsResourceUri, identityDocument, opts, sysLogger)
					if err != nil {
						errors <- fmt.Errorf("Cannot get attestation data: %v\n", err)
						return
					}
					err = sia.RefreshInstance(data, ztsUrl, identityDocument, opts, sysLogger)
					if err != nil {
						errors <- fmt.Errorf("refresh identity failed, error: %v", err)
						return
					}
					logutil.LogInfo(sysLogger, "identity successfully refreshed for services: %s\n", svcs)
				} else {
					initialSetup = false
				}
				sia.GetRoleCertificate(ztsUrl,
					fmt.Sprintf("%s/%s.%s.key.pem", opts.KeyDir, opts.Domain, opts.Services[0].Name),
					fmt.Sprintf("%s/%s.%s.cert.pem", opts.CertDir, opts.Domain, opts.Services[0].Name),
					opts,
					sysLogger,
				)
				select {
				case <-stop:
					errors <- nil
					return
				case <-time.After(rotationInterval):
					break
				}
			}
		}()

		go func() {
			signals := make(chan os.Signal, 2)
			signal.Notify(signals, os.Interrupt, syscall.SIGTERM)
			sig := <-signals
			logutil.LogInfo(sysLogger, "Received signal %v, stopping rotation\n", sig)
			stop <- true
		}()

		err = <-errors
		if err != nil {
			logutil.LogInfo(sysLogger, "%v\n", err)
		}
	}
	os.Exit(0)
}

// getAttestationData fetches attestation data for all the services mentioned in the config file
func getAttestationData(resourceUri string, identityDocument *attestation.IdentityDocument, opts *options.Options, sysLogger io.Writer) ([]*attestation.Data, error) {
	var data []*attestation.Data
	for _, svc := range opts.Services {
		a, err := attestation.New(opts.Domain, svc.Name, MetaEndPoint, ApiVersion, resourceUri, identityDocument, sysLogger)
		if err != nil {
			return nil, err
		}
		data = append(data, a)
	}
	return data, nil
}


text:
namespace {

class SystemThemeX11 : public CustomThemeSupplier {
 public:
  explicit SystemThemeX11(PrefService* pref_service);

  // Overridden from CustomThemeSupplier:
  void StartUsingTheme() override;
  void StopUsingTheme() override;
  bool GetTint(int id, color_utils::HSL* hsl) const override;
  bool GetColor(int id, SkColor* color) const override;
  bool GetDisplayProperty(int id, int* result) const override;
  gfx::Image GetImageNamed(int id) const override;
  bool HasCustomImage(int id) const override;

 private:
  ~SystemThemeX11() override;

  // These pointers are not owned by us.
  views::LinuxUI* const linux_ui_;
  PrefService* const pref_service_;

  DISALLOW_COPY_AND_ASSIGN(SystemThemeX11);
};

SystemThemeX11::SystemThemeX11(PrefService* pref_service)
    : CustomThemeSupplier(NATIVE_X11),
      linux_ui_(views::LinuxUI::instance()),
      pref_service_(pref_service) {}

void SystemThemeX11::StartUsingTheme() {
  pref_service_->SetBoolean(prefs::kUsesSystemTheme, true);
  // Have the former theme notify its observers of change.
  ui::NativeTheme::GetInstanceForNativeUi()->NotifyObservers();
}

void SystemThemeX11::StopUsingTheme() {
  pref_service_->SetBoolean(prefs::kUsesSystemTheme, false);
  // Have the former theme notify its observers of change.
  if (linux_ui_)
    linux_ui_->GetNativeTheme(nullptr)->NotifyObservers();
}

bool SystemThemeX11::GetTint(int id, color_utils::HSL* hsl) const {
  return linux_ui_ && linux_ui_->GetTint(id, hsl);
}

bool SystemThemeX11::GetColor(int id, SkColor* color) const {
  return linux_ui_ && linux_ui_->GetColor(id, color,
                                          pref_service_->GetBoolean(
                                              prefs::kUseCustomChromeFrame));
}

bool SystemThemeX11::GetDisplayProperty(int id, int* result) const {
  return linux_ui_ && linux_ui_->GetDisplayProperty(id, result);
}

gfx::Image SystemThemeX11::GetImageNamed(int id) const {
  return gfx::Image();
}

bool SystemThemeX11::HasCustomImage(int id) const {
  return false;
}

SystemThemeX11::~SystemThemeX11() {}

}  // namespace

ThemeServiceAuraLinux::~ThemeServiceAuraLinux() = default;

bool ThemeServiceAuraLinux::ShouldInitWithSystemTheme() const {
  return ShouldUseSystemThemeForProfile(profile());
}

void ThemeServiceAuraLinux::UseSystemTheme() {
  SetCustomDefaultTheme(new SystemThemeX11(profile()->GetPrefs()));
}

bool ThemeServiceAuraLinux::IsSystemThemeDistinctFromDefaultTheme() const {
  return true;
}

bool ThemeServiceAuraLinux::UsingSystemTheme() const {
  return GetThemeSupplier() && GetThemeSupplier()->get_theme_type() ==
                                   CustomThemeSupplier::NATIVE_X11;
}

void ThemeServiceAuraLinux::FixInconsistentPreferencesIfNeeded() {
  PrefService* prefs = profile()->GetPrefs();

  // When using the system theme, the theme ID should match the default. Give
  // precedence to the non-default theme specified.
  if (GetThemeID() != ThemeHelper::kDefaultThemeID &&
      prefs->GetBoolean(prefs::kUsesSystemTheme)) {
    prefs->SetBoolean(prefs::kUsesSystemTheme, false);
  }
}

// static
bool ThemeServiceAuraLinux::ShouldUseSystemThemeForProfile(
    const Profile* profile) {
  return !profile || (!profile->IsSupervised() &&
                      profile->GetPrefs()->GetBoolean(prefs::kUsesSystemTheme));
}


text:
            <button mat-button (click)="fitColumnWidths()">Reformat table (R)</button>

            <button mat-button (click)="setAllColumnsVisible()">Visible all (V)</button>

            <button mat-button (click)="clearAllFilters()">Clear all filters (C)</button>

    <ag-grid-angular
        #agGrid
        style="width: 100%; height: 500px;"
        class="ag-theme-balham"
        pagination
        animateRows
        floatingFilter
        [rowData]="tableRowData"
        [defaultColDef]="defaultColDef"
        [columnDefs]="columnDefs"
        [rowClassRules]="rowClassRules"
        (gridReady)="handleGridReady($event)"
        (columnGroupOpened)="fitColumnWidths()"
        (modelUpdated)="handleModelUpdated()"
        (rowClicked)="handleRowClicked($event)"
        (columnVisible)="fitTableWidth()"
    >
    </ag-grid-angular>


text:
package bookStore;

public class Book {

	private String author;
	private String bookName;
	private Double price;

	public Book(String bookName, Double price, String author) {
		this.author = author;
		this.bookName = bookName;
		this.price = price;
	}

	public String getAuthor() {
		return this.author;
	}

	public Double getPrice() {
		return this.price;
	}

	public String getBookName() {
		return bookName;
	}

}


text:
Start blogging w/ this Simple static blog generator.

* 88 lines of code.
* ***EASY*** to use and extend.
* Post format is compatible with *Jekyll*, and most other generators.

**Check [https://oxal.org/usr/stab](https://oxal.org/usr/stab) for
complete documentation.**

## Quickstart

```sh
# This is the default template to start with
git clone https://github.com/oxalorg/Stab-site/

# Create a virtualenv if you wish to
# virtualenv venv
# source venv/bin/activate

# Install `stab` from pypi
pip3 install stab

# Now you can traverse the folder to learn how stab works
# It's very intuitive, to know more go to docs

# Build site using
stab .
# or alternatively
# stab /path/to/folder
```


text:
var logger = require('koa-logger');
var route = require('koa-route');
var cors = require('koa-cors');
var serve = require('koa-static');
var koa = require('koa');
var app = koa();

// Rethink configuration
var r = require("rethinkdb");

var databaseConfig = {
    db: "earthquake",
    host: "localhost",
    port: 28015
};

var rrun = function *(query) {
    var connection = yield r.connect(databaseConfig);

    var result = yield query.run(connection);

    if (connection) {
        connection.close();
    }

    return result;
};

// Middleware
app.use(logger());
app.use(cors());

// Static website
app.use(serve('dist'));

// API
app.use(route.get('/api/quakes', function *() {
    this.body = yield rrun(
        r.table("quakes").orderBy(
            r.desc(r.row("mag")))
    );
}));

app.use(route.get('/api/quakes/nearest', function *() {
    var range = parseFloat(this.query.range || 100),
        latitude = parseFloat(this.query.lat),
        longitude = parseFloat(this.query.long);

    this.body = yield rrun(
        r.table("quakes").getNearest(
            r.point(longitude, latitude),
            { index: 'geometry', unit: 'mi', maxDist: range })
    );
}));

app.listen(3050);


text:
/*
 * This class implements a FIR bandpass filter using a FFT convolution algorithm
 * The filter is complex and is specified with 3 parameters: sample frequency,
 * high cut-off and low cut-off frequency
 */
#pragma once

#include "common/datatypes.h"
#include "cute_fft.h"

class FastFIR
{
public:
    FastFIR();
    virtual    ~FastFIR();

    /*
     * Setup filter parameters
     *   low_cut   Low cutoff frequency of filter in Hz
     *   high_cut  High cutoff frequency of filter in Hz
     *   cw_offs   The CW tone frequency.
     *   fs        Sample rate in Hz.
     *
     * Cutoff frequencies range from -SampleRate/2 to +SampleRate/2
     * high_cut must be greater than low_cut
     */
    void        setup(real_t low_cut, real_t high_cut, real_t cw_offs, real_t fs);
    void        set_sample_rate(real_t new_rate);

    /*
     * Process complex samples
     *   num      The number of complex samples in the input buffer.
     *   inbuf    Input buffer.
     *   outbuf   Outbut buffer.
     *
     * Returns the number of complex samples placed in the output buffer.
     *
     * The number of samples returned in general will not be equal to the number
     * of input samples due to FFT block size processing.
     */
    int         process(int num, complex_t * inbuf, complex_t * outbuf);

private:
    inline void cpx_mpy(int N, complex_t * m, complex_t * src, complex_t * dest);
    void        free_memory();

    real_t      locut;
    real_t      hicut;
    real_t      offset;
    real_t      samprate;

    unsigned int    inbuf_inpos;
    real_t     *window;         // window coefficients
    complex_t  *fftbuf;         // FFT buffer
    complex_t  *fftovrbuf;      // FFT overlap buffer
    complex_t  *filter_coef;    // Filter coefficients

    CuteFft     m_Fft;
};


text:
namespace RemotingHostSample
{
    // This sample renderer instantiates a basic rendering pipeline.
    class SpinningCubeRenderer
    {
    public:
        SpinningCubeRenderer(const std::shared_ptr<DX::DeviceResources>& deviceResources);
        void CreateWindowSizeDependentResources();
        void CreateDeviceDependentResources();
        void ReleaseDeviceDependentResources();
        void Update(const DX::StepTimer& timer);
        void SetColorFilter(DirectX::XMFLOAT4 color);
        void Render(bool isStereo);

        // Repositions the sample hologram.
        void PositionHologram(Windows::UI::Input::Spatial::SpatialPointerPose^ pointerPose);

        // Repositions the sample hologram, using direct measures.
        void PositionHologram(Windows::Foundation::Numerics::float3 pos, Windows::Foundation::Numerics::float3 dir);

        // Property accessors.
        void SetPosition(Windows::Foundation::Numerics::float3 pos) { m_position = pos;  }
        Windows::Foundation::Numerics::float3 GetPosition()         { return m_position; }

        void Pause() { m_pauseState = PauseState::Pausing; }
        void Unpause() { m_pauseState = PauseState::Unpausing; }

    private:
        enum class PauseState
        {
            Unpaused = 0,
            Pausing,
            Paused,
            Unpausing,
        };

        // Cached pointer to device resources.
        std::shared_ptr<DX::DeviceResources>            m_deviceResources;

        // Direct3D resources for cube geometry.
        Microsoft::WRL::ComPtr<ID3D11InputLayout>       m_inputLayout;
        Microsoft::WRL::ComPtr<ID3D11Buffer>            m_vertexBuffer;
        Microsoft::WRL::ComPtr<ID3D11Buffer>            m_indexBuffer;
        Microsoft::WRL::ComPtr<ID3D11VertexShader>      m_vertexShader;
        Microsoft::WRL::ComPtr<ID3D11GeometryShader>    m_geometryShader;
        Microsoft::WRL::ComPtr<ID3D11PixelShader>       m_pixelShader;
        Microsoft::WRL::ComPtr<ID3D11Buffer>            m_modelConstantBuffer;
        Microsoft::WRL::ComPtr<ID3D11Buffer>            m_filterColorBuffer;

        // System resources for cube geometry.
        ModelConstantBuffer                             m_modelConstantBufferData;
        uint32                                          m_indexCount = 0;
        DirectX::XMFLOAT4                               m_filterColorData = { 1, 1, 1, 1 };

        // Variables used with the rendering loop.
        bool                                            m_loadingComplete = false;
        float                                           m_degreesPerSecond = 45.f;
        Windows::Foundation::Numerics::float3           m_position = { 0.f, 0.f, -2.f };
        PauseState                                      m_pauseState = PauseState::Unpaused;
        double                                          m_rotationOffset = 0;

        // If the current D3D Device supports VPRT, we can avoid using a geometry
        // shader just to set the render target array index.
        bool                                            m_usingVprtShaders = false;
    };
}


text:
import flask

import pymysql.cursors

def get_member_data(user_id, fields=None):
    """
    Queries the database and returns member data for the specified user_id
    or list of user_id's.

    Arguments:
        user_id: The member (or list of members) to look up
        fields:  The fields to return. If None specified, then default_fields
                 are used.
    Returns:
        result: The fields and corresponding values of member with user_id. In
                the form of a dict with key:value of columnname:columnvalue.
                For lists of user_id's result will be a list of dicts.
    """
    all_returnable_fields = [
        "user_id", "uid", "last_name", "first_name", "middle_name",
        "preferred_name", "email", "phone", "gender", "gender_custom",
        "birthday", "entry_year", "graduation_year", "msc", "building",
        "room_num", "address", "city", "state", "zip", "country"
    ]
    default_fields = [
        "user_id", "first_name", "last_name", "email", "uid", "entry_year",
        "graduation_year"
    ]
    if fields == None:
        fields = default_fields
    else:
        if any(f not in all_returnable_fields for f in fields):
            return "Invalid field"

    if not isinstance(user_id, list):
        user_id = [user_id]

    # edge case: user_id is empty list
    if len(user_id) == 0:
        return {}

    query = "SELECT " + ', '.join(fields) + " FROM members WHERE "
    query += ' OR '.join(["user_id=%s" for _ in user_id])

    # Execute the query
    with flask.g.pymysql_db.cursor() as cursor:
        cursor.execute(query, user_id)
        result = cursor.fetchall()

    if len(result) == 0:
        return {}
    elif len(result) == 1:
        return result[0]
    return result

def get_member_list_data(fields=None, attrs={}):
    """
    Queries the database and returns list of member data constrained by the
    specified attributes.

    Arguments:
        fields: The fields to return. If None specified, then default_fields
                are used.
        attrs:  The attributes of the members to filter for.
    Returns:
        result: The fields and corresponding values of members with desired
                attributes. In the form of a list of dicts with key:value of
                columnname:columnvalue.
    """
    all_returnable_fields = [
        "user_id", "uid", "last_name", "first_name", "middle_name", "email",
        "phone", "gender", "gender_custom", "birthday", "entry_year",
        "graduation_year", "msc", "building", "room_num", "address", "city",
        "state", "zip", "country"
    ]
    default_fields = [
        "user_id", "first_name", "last_name", "email", "uid", "entry_year",
        "graduation_year"
    ]
    if fields == None:
        fields = default_fields
    else:
        if any(f not in all_returnable_fields for f in fields):
            return "Invalid field"

    query = "SELECT " + ', '.join(fields) + " FROM members"

    if attrs:
        query += " WHERE "
        query += ' AND '.join([key + "= %s" for key, value in attrs.items()])
    values = [value for key, value in attrs.items()]

    # Execute the query
    with flask.g.pymysql_db.cursor() as cursor:
        cursor.execute(query, values)
        return cursor.fetchall()

def get_name_and_email(user_id):
    """
    Queries the database and returns the full_name and email corresponding to the
    user_id.

    Arguments:
        user_id:            The user_id to match.
    Returns:
        {'full_name', 'email'}: The full_name and email of the user with the given id.
    """

    query = """
        SELECT full_name, email
        FROM members NATURAL LEFT JOIN members_full_name
        WHERE user_id = %s
    """
    with flask.g.pymysql_db.cursor() as cursor:
        cursor.execute(query, user_id)
        return cursor.fetchone()

def get_group_list_of_member(user_id):
    """
    Queries the database and returns list of groups and admin status
    for a given id
    Arguments:
        user_id: The user_id for query.
    Returns:
        result: All the groups that an user_id is a part of
    """
    query = """
        SELECT DISTINCT group_id, group_name, control
        FROM groups NATURAL JOIN positions NATURAL JOIN current_position_holders
        WHERE user_id = %s
    """

    with flask.g.pymysql_db.cursor() as cursor:
        cursor.execute(query, [user_id])
        return list(cursor.fetchall())

def set_image(user_id, extension, contents):
    delete_query = 'DELETE FROM images WHERE user_id = %s'
    with flask.g.pymysql_db.cursor() as cursor:
        cursor.execute(delete_query, [user_id])
    add_query = 'INSERT INTO images (user_id, extension, image) VALUES (%s, %s, %s)'
    with flask.g.pymysql_db.cursor() as cursor:
        cursor.execute(add_query, [user_id, extension, contents])

def get_preferred_name(user_id):
    return get_member_data(user_id, ['preferred_name'])['preferred_name'] or ''

def get_gender(user_id):
    return get_member_data(user_id, ['gender_custom'])['gender_custom'] or ''

def set_member_field(user_id, field, value):
    query = 'UPDATE members SET `' + field + '` = %s WHERE user_id = %s'
    with flask.g.pymysql_db.cursor() as cursor:
        cursor.execute(query, [value, user_id])

def get_news():
    query = 'SELECT * FROM news ORDER BY news_id DESC'
    with flask.g.pymysql_db.cursor() as cursor:
        cursor.execute(query)
        return cursor.fetchall()

def add_news(news):
    query = 'INSERT INTO news(news_text) VALUES (%s)'
    with flask.g.pymysql_db.cursor() as cursor:
        cursor.execute(query, news)

def delete_news(news_id):
    query = 'DELETE FROM news WHERE news_id = %s'
    with flask.g.pymysql_db.cursor() as cursor:
        cursor.execute(query, news_id)


text:
package com.facebook.buck.shell;

import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.rules.BuildRuleParams;
import com.facebook.buck.rules.BuildRuleResolver;
import com.facebook.buck.rules.BuildRuleType;
import com.facebook.buck.rules.Description;
import com.facebook.buck.rules.SourcePath;
import com.facebook.buck.rules.SourcePathResolver;
import com.facebook.buck.rules.TargetGraph;
import com.facebook.infer.annotation.SuppressFieldNotInitialized;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;

public class ShBinaryDescription implements Description<ShBinaryDescription.Arg> {

  private static final BuildRuleType TYPE = BuildRuleType.of("sh_binary");

  @Override
  public BuildRuleType getBuildRuleType() {
    return TYPE;
  }

  @Override
  public Arg createUnpopulatedConstructorArg() {
    return new Arg();
  }

  @Override
  public <A extends Arg> ShBinary createBuildRule(
      TargetGraph targetGraph,
      BuildRuleParams params,
      BuildRuleResolver resolver,
      A args) {
    return new ShBinary(params, new SourcePathResolver(resolver), args.main, args.resources.get());
  }

  @SuppressFieldNotInitialized
  public static class Arg {
    public SourcePath main;

    public Optional<ImmutableSortedSet<BuildTarget>> deps;

    public Optional<ImmutableSet<SourcePath>> resources;
  }
}


text:
from __future__ import unicode_literals

from django.db import models
from django.utils.encoding import python_2_unicode_compatible

@python_2_unicode_compatible
class Building(models.Model):
    name = models.CharField(max_length=10)

    def __str__(self):
        return "Building: %s" % self.name

@python_2_unicode_compatible
class Device(models.Model):
    building = models.ForeignKey('Building')
    name = models.CharField(max_length=10)

    def __str__(self):
        return "device '%s' in building %s" % (self.name, self.building)

@python_2_unicode_compatible
class Port(models.Model):
    device = models.ForeignKey('Device')
    port_number = models.CharField(max_length=10)

    def __str__(self):
        return "%s/%s" % (self.device.name, self.port_number)

@python_2_unicode_compatible
class Connection(models.Model):
    start = models.ForeignKey(Port, related_name='connection_start',
            unique=True)
    end = models.ForeignKey(Port, related_name='connection_end', unique=True)

    def __str__(self):
        return "%s to %s" % (self.start, self.end)

# Another non-tree hierarchy that exercises code paths similar to the above
# example, but in a slightly different configuration.
class TUser(models.Model):
    name = models.CharField(max_length=200)

class Person(models.Model):
    user = models.ForeignKey(TUser, unique=True)

class Organizer(models.Model):
    person = models.ForeignKey(Person)

class Student(models.Model):
    person = models.ForeignKey(Person)

class Class(models.Model):
    org = models.ForeignKey(Organizer)

class Enrollment(models.Model):
    std = models.ForeignKey(Student)
    cls = models.ForeignKey(Class)

# Models for testing bug #8036.
class Country(models.Model):
    name = models.CharField(max_length=50)

class State(models.Model):
    name = models.CharField(max_length=50)
    country = models.ForeignKey(Country)

class ClientStatus(models.Model):
    name = models.CharField(max_length=50)

class Client(models.Model):
    name = models.CharField(max_length=50)
    state = models.ForeignKey(State, null=True)
    status = models.ForeignKey(ClientStatus)

class SpecialClient(Client):
    value = models.IntegerField()

# Some model inheritance exercises
@python_2_unicode_compatible
class Parent(models.Model):
    name = models.CharField(max_length=10)

    def __str__(self):
        return self.name

class Child(Parent):
    value = models.IntegerField()

@python_2_unicode_compatible
class Item(models.Model):
    name = models.CharField(max_length=10)
    child = models.ForeignKey(Child, null=True)

    def __str__(self):
        return self.name

# Models for testing bug #19870.
@python_2_unicode_compatible
class Fowl(models.Model):
    name = models.CharField(max_length=10)

    def __str__(self):
        return self.name

class Hen(Fowl):
    pass

class Chick(Fowl):
    mother = models.ForeignKey(Hen)

class Base(models.Model):
    name = models.CharField(max_length=10)
    lots_of_text = models.TextField()

    class Meta:
        abstract = True

class A(Base):
    a_field = models.CharField(max_length=10)

class B(Base):
    b_field = models.CharField(max_length=10)

class C(Base):
    c_a = models.ForeignKey(A)
    c_b = models.ForeignKey(B)
    is_published = models.BooleanField(default=False)


text:
using UnityEngine;

public class PlayerDeath : MonoBehaviour
{
	public void OnHitByWave()
	{
		Debug.Log("player died!");
		var guiManager = GuiManager.Instance;
		if (guiManager != null)
		{
			guiManager.EndGame();
		}
	}
}


text:
/*
 * Do not modify this file. This file is generated from the dynamodb-2012-08-10.normal.json service model.
 */
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;

using Amazon.Runtime;
using Amazon.Runtime.Internal;

namespace Amazon.DynamoDBv2.Model
{
    ///
    /// Container for the parameters to the UpdateTable operation.
    /// Updates the provisioned throughput for the given table, or manages the global secondary
    /// indexes on the table.
    ///
    ///
    /// <para>
    /// You can increase or decrease the table's provisioned throughput values within the
    /// maximums and minimums listed in the Limits
    /// section in the Amazon DynamoDB Developer Guide.
    /// </para>
    ///
    /// <para>
    /// In addition, you can use UpdateTable to add, modify or delete global secondary
    /// indexes on the table. For more information, see Managing
    /// Global Secondary Indexes in the Amazon DynamoDB Developer Guide.
    /// </para>
    ///
    /// <para>
    /// The table must be in the ACTIVE state for UpdateTable to succeed.
    /// UpdateTable is an asynchronous operation; while executing the operation, the
    /// table is in the UPDATING state. While the table is in the UPDATING
    /// state, the table still has the provisioned throughput from before the call. The table's
    /// new provisioned throughput settings go into effect when the table returns to the ACTIVE
    /// state; at that point, the UpdateTable operation is complete.
    /// </para>
    ///
    public partial class UpdateTableRequest : AmazonDynamoDBRequest
    {
        private List<AttributeDefinition> _attributeDefinitions = new List<AttributeDefinition>();
        private List<GlobalSecondaryIndexUpdate> _globalSecondaryIndexUpdates = new List<GlobalSecondaryIndexUpdate>();
        private ProvisionedThroughput _provisionedThroughput;
        private string _tableName;

        ///
        /// Empty constructor used to set  properties independently even when a simple constructor is available
        ///
        public UpdateTableRequest() { }

        ///
        /// Instantiates UpdateTableRequest with the parameterized properties
        ///
        /// <param name="tableName">The name of the table to be updated.</param>
        /// <param name="provisionedThroughput">Sets the UpdateTableRequest ProvisionedThroughput property</param>
        public UpdateTableRequest(string tableName, ProvisionedThroughput provisionedThroughput)
        {
            _tableName = tableName;
            _provisionedThroughput = provisionedThroughput;
        }

        ///
        /// Gets and sets the property AttributeDefinitions.
        /// <para>
        /// An array of attributes that describe the key schema for the table and indexes. If
        /// you are adding a new global secondary index to the table, AttributeDefinitions
        /// must include the key element(s) of the new index.
        /// </para>
        ///
        public List<AttributeDefinition> AttributeDefinitions
        {
            get { return this._attributeDefinitions; }
            set { this._attributeDefinitions = value; }
        }

        // Check to see if AttributeDefinitions property is set
        internal bool IsSetAttributeDefinitions()
        {
            return this._attributeDefinitions != null && this._attributeDefinitions.Count > 0;
        }

        ///
        /// Gets and sets the property GlobalSecondaryIndexUpdates.
        /// <para>
        /// An array of one or more global secondary indexes for the table. For each index in
        /// the array, you can request one action:
        /// </para>
        ///

        /// <para>
        /// Create - add a new global secondary index to the table.
        /// </para>
        ///

        /// <para>
        /// Update - modify the provisioned throughput settings of an existing global secondary
        /// index.
        /// </para>
        ///

        /// <para>
        /// Delete - remove a global secondary index from the table.
        /// </para>
        ///

        ///
        public List<GlobalSecondaryIndexUpdate> GlobalSecondaryIndexUpdates
        {
            get { return this._globalSecondaryIndexUpdates; }
            set { this._globalSecondaryIndexUpdates = value; }
        }

        // Check to see if GlobalSecondaryIndexUpdates property is set
        internal bool IsSetGlobalSecondaryIndexUpdates()
        {
            return this._globalSecondaryIndexUpdates != null && this._globalSecondaryIndexUpdates.Count > 0;
        }

        ///
        /// Gets and sets the property ProvisionedThroughput.
        ///
        public ProvisionedThroughput ProvisionedThroughput
        {
            get { return this._provisionedThroughput; }
            set { this._provisionedThroughput = value; }
        }

        // Check to see if ProvisionedThroughput property is set
        internal bool IsSetProvisionedThroughput()
        {
            return this._provisionedThroughput != null;
        }

        ///
        /// Gets and sets the property TableName.
        /// <para>
        /// The name of the table to be updated.
        /// </para>
        ///
        public string TableName
        {
            get { return this._tableName; }
            set { this._tableName = value; }
        }

        // Check to see if TableName property is set
        internal bool IsSetTableName()
        {
            return this._tableName != null;
        }

    }
}


text:
<?xml version="1.0" encoding="UTF-8" ?>
<class name="StreamPeerTCP" inherits="StreamPeer" version="4.0">
	<brief_description>
		TCP stream peer.
	</brief_description>
	<description>
		TCP stream peer. This object can be used to connect to TCP servers, or also is returned by a TCP server.
	</description>
	<tutorials>
	</tutorials>
	<methods>
		<method name="connect_to_host">
			<return type="int" enum="Error">
			</return>
			<argument index="0" name="host" type="String">
			</argument>
			<argument index="1" name="port" type="int">
			</argument>
			<description>
				Connects to the specified [code]host:port[/code] pair. A hostname will be resolved if valid. Returns [constant OK] on success or [constant FAILED] on failure.
			</description>
		</method>
		<method name="disconnect_from_host">
			<return type="void">
			</return>
			<description>
				Disconnects from host.
			</description>
		</method>
		<method name="get_connected_host" qualifiers="const">
			<return type="String">
			</return>
			<description>
				Returns the IP of this peer.
			</description>
		</method>
		<method name="get_connected_port" qualifiers="const">
			<return type="int">
			</return>
			<description>
				Returns the port of this peer.
			</description>
		</method>
		<method name="get_status">
			<return type="int" enum="StreamPeerTCP.Status">
			</return>
			<description>
				Returns the status of the connection, see [enum Status].
			</description>
		</method>
		<method name="is_connected_to_host" qualifiers="const">
			<return type="bool">
			</return>
			<description>
				Returns [code]true[/code] if this peer is currently connected to a host, [code]false[/code] otherwise.
			</description>
		</method>
		<method name="set_no_delay">
			<return type="void">
			</return>
			<argument index="0" name="enabled" type="bool">
			</argument>
			<description>
				Disables Nagle's algorithm to improve latency for small packets.
				[b]Note:[/b] For applications that send large packets or need to transfer a lot of data, this can decrease the total available bandwidth.
			</description>
		</method>
	</methods>
	<constants>
		<constant name="STATUS_NONE" value="0" enum="Status">
			The initial status of the [StreamPeerTCP]. This is also the status after disconnecting.
		</constant>
		<constant name="STATUS_CONNECTING" value="1" enum="Status">
			A status representing a [StreamPeerTCP] that is connecting to a host.
		</constant>
		<constant name="STATUS_CONNECTED" value="2" enum="Status">
			A status representing a [StreamPeerTCP] that is connected to a host.
		</constant>
		<constant name="STATUS_ERROR" value="3" enum="Status">
			A status representing a [StreamPeerTCP] in error state.
		</constant>
	</constants>
</class>


text:
using System;
using System.Runtime.InteropServices;

namespace LibuvSharp
{
	[StructLayout(LayoutKind.Sequential)]
	internal struct uv_connect_t
	{
		public RequestType type;
		public IntPtr data;
		/*
		#if !__MonoCS__
		NativeOverlapped overlapped;
		IntPtr queued_bytes;
		uv_err_t error;
		IntPtr next_req;
		#endif
		*/
		public IntPtr cb;
		public IntPtr handle;
	}

	unsafe internal class ConnectRequest : CallbackPermaRequest
	{
		uv_connect_t *connect;

		public ConnectRequest()
			: base(RequestType.UV_CONNECT)
		{
			connect = (uv_connect_t *)Handle;
		}

		public IntPtr ConnectHandle {
			get {
				return connect->handle;
			}
		}
	}
}


text:
package com.planet_ink.coffee_mud.Abilities.Diseases;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;

import java.util.*;

public class Disease_Chlamydia extends Disease
{
	@Override public String ID() { return "Disease_Chlamydia"; }
	private final static String localizedName = CMLib.lang().L("Chlamydia");
	@Override public String name() { return localizedName; }
	private final static String localizedStaticDisplay = CMLib.lang().L("(Chlamydia)");
	@Override public String displayText() { return localizedStaticDisplay; }
	@Override protected int canAffectCode(){return CAN_MOBS;}
	@Override protected int canTargetCode(){return CAN_MOBS;}
	@Override public int abstractQuality(){return Ability.QUALITY_MALICIOUS;}
	@Override public boolean putInCommandlist(){return false;}
	@Override public int difficultyLevel(){return 5;}

	@Override protected int DISEASE_TICKS(){return CMProps.getIntVar(CMProps.Int.TICKSPERMUDDAY)*10;}
	@Override protected int DISEASE_DELAY(){return CMProps.getIntVar(CMProps.Int.TICKSPERMUDDAY);}
	@Override protected String DISEASE_DONE(){return L("Your chlamydia clears up.");}
	@Override protected String DISEASE_START(){return L("^G<S-NAME> scratch(es) <S-HIS-HER> privates.^?");}
	@Override protected String DISEASE_AFFECT(){return L("<S-NAME> scratch(es) <S-HIS-HER> privates.");}
	@Override public int spreadBitmap(){return DiseaseAffect.SPREAD_STD;}

	@Override
	public boolean tick(Tickable ticking, int tickID)
	{
		if(!super.tick(ticking,tickID))
			return false;
		if(affected==null)
			return false;
		if(!(affected instanceof MOB))
			return true;

		final MOB mob=(MOB)affected;
		if((!mob.amDead())&&((--diseaseTick)<=0))
		{
			diseaseTick=DISEASE_DELAY();
			mob.location().show(mob,null,CMMsg.MSG_NOISE,DISEASE_AFFECT());
			return true;
		}
		return true;
	}

	@Override
	public void affectCharState(MOB affected, CharState affectableState)
	{
		super.affectCharState(affected,affectableState);
		affectableState.setMovement(affectableState.getMovement()/2);
	}

	@Override
	public boolean okMessage(final Environmental myHost, final CMMsg msg)
	{
		if(affected==null)
			return super.okMessage(myHost,msg);
		if(affected instanceof MOB)
		{
			final MOB mob=(MOB)affected;
			if(((msg.amITarget(mob))||(msg.amISource(mob)))
			&&(msg.tool() instanceof Social)
			&&(msg.tool().Name().equals("MATE <T-NAME>")
			||msg.tool().Name().equals("SEX <T-NAME>")))
			{
				msg.source().tell(mob,null,null,L("<S-NAME> really do(es)n't feel like it."));
				return false;
			}
		}
		return super.okMessage(myHost,msg);
	}
}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace OSky.Web.Http.Formattings
{
    public class PlainTextFormatter : MediaTypeFormatter
    {
        public PlainTextFormatter()
        {
            SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/plain"));
        }

        public override bool CanReadType(Type type)
        {
            return type == typeof(string);
        }

        public override bool CanWriteType(Type type)
        {
            return type == typeof(string);
        }

        public override Task<object> ReadFromStreamAsync(Type type, Stream stream, HttpContent content, IFormatterLogger formatterLogger)
        {
            var reader = new StreamReader(stream);
            string value = reader.ReadToEnd();

            var tcs = new TaskCompletionSource<object>();
            tcs.SetResult(value);
            return tcs.Task;
        }

        public override Task WriteToStreamAsync(Type type, object value, Stream stream, HttpContent content, TransportContext transportContext)
        {
            var writer = new StreamWriter(stream);
            writer.Write((string)value);
            writer.Flush();

            var tcs = new TaskCompletionSource<object>();
            tcs.SetResult(null);
            return tcs.Task;
        }
    }
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.serviceusage.v1beta1.model;

/**
 * A quota bucket is a quota provisioning unit for a specific set of dimensions.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Service Usage API. For a detailed explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class QuotaBucket extends com.google.api.client.json.GenericJson {

  /**
   * Admin override on this quota bucket.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private QuotaOverride adminOverride;

  /**
   * Consumer override on this quota bucket.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private QuotaOverride consumerOverride;

  /**
   * The default limit of this quota bucket, as specified by the service configuration.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key @com.google.api.client.json.JsonString
  private java.lang.Long defaultLimit;

  /**
   * The dimensions of this quota bucket. If this map is empty, this is the global bucket, which is
   * the default quota value applied to all requests that do not have a more specific override. If
   * this map is nonempty, the default limit, effective limit, and quota overrides apply only to
   * requests that have the dimensions given in the map. For example, if the map has key `region`
   * and value `us-east-1`, then the specified effective limit is only effective in that region, and
   * the specified overrides apply only in that region.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.util.Map<String, java.lang.String> dimensions;

  /**
   * The effective limit of this quota bucket. Equal to default_limit if there are no overrides.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key @com.google.api.client.json.JsonString
  private java.lang.Long effectiveLimit;

  /**
   * Producer override on this quota bucket.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private QuotaOverride producerOverride;

  /**
   * Admin override on this quota bucket.
   * @return value or {@code null} for none
   */
  public QuotaOverride getAdminOverride() {
    return adminOverride;
  }

  /**
   * Admin override on this quota bucket.
   * @param adminOverride adminOverride or {@code null} for none
   */
  public QuotaBucket setAdminOverride(QuotaOverride adminOverride) {
    this.adminOverride = adminOverride;
    return this;
  }

  /**
   * Consumer override on this quota bucket.
   * @return value or {@code null} for none
   */
  public QuotaOverride getConsumerOverride() {
    return consumerOverride;
  }

  /**
   * Consumer override on this quota bucket.
   * @param consumerOverride consumerOverride or {@code null} for none
   */
  public QuotaBucket setConsumerOverride(QuotaOverride consumerOverride) {
    this.consumerOverride = consumerOverride;
    return this;
  }

  /**
   * The default limit of this quota bucket, as specified by the service configuration.
   * @return value or {@code null} for none
   */
  public java.lang.Long getDefaultLimit() {
    return defaultLimit;
  }

  /**
   * The default limit of this quota bucket, as specified by the service configuration.
   * @param defaultLimit defaultLimit or {@code null} for none
   */
  public QuotaBucket setDefaultLimit(java.lang.Long defaultLimit) {
    this.defaultLimit = defaultLimit;
    return this;
  }

  /**
   * The dimensions of this quota bucket. If this map is empty, this is the global bucket, which is
   * the default quota value applied to all requests that do not have a more specific override. If
   * this map is nonempty, the default limit, effective limit, and quota overrides apply only to
   * requests that have the dimensions given in the map. For example, if the map has key `region`
   * and value `us-east-1`, then the specified effective limit is only effective in that region, and
   * the specified overrides apply only in that region.
   * @return value or {@code null} for none
   */
  public java.util.Map<String, java.lang.String> getDimensions() {
    return dimensions;
  }

  /**
   * The dimensions of this quota bucket. If this map is empty, this is the global bucket, which is
   * the default quota value applied to all requests that do not have a more specific override. If
   * this map is nonempty, the default limit, effective limit, and quota overrides apply only to
   * requests that have the dimensions given in the map. For example, if the map has key `region`
   * and value `us-east-1`, then the specified effective limit is only effective in that region, and
   * the specified overrides apply only in that region.
   * @param dimensions dimensions or {@code null} for none
   */
  public QuotaBucket setDimensions(java.util.Map<String, java.lang.String> dimensions) {
    this.dimensions = dimensions;
    return this;
  }

  /**
   * The effective limit of this quota bucket. Equal to default_limit if there are no overrides.
   * @return value or {@code null} for none
   */
  public java.lang.Long getEffectiveLimit() {
    return effectiveLimit;
  }

  /**
   * The effective limit of this quota bucket. Equal to default_limit if there are no overrides.
   * @param effectiveLimit effectiveLimit or {@code null} for none
   */
  public QuotaBucket setEffectiveLimit(java.lang.Long effectiveLimit) {
    this.effectiveLimit = effectiveLimit;
    return this;
  }

  /**
   * Producer override on this quota bucket.
   * @return value or {@code null} for none
   */
  public QuotaOverride getProducerOverride() {
    return producerOverride;
  }

  /**
   * Producer override on this quota bucket.
   * @param producerOverride producerOverride or {@code null} for none
   */
  public QuotaBucket setProducerOverride(QuotaOverride producerOverride) {
    this.producerOverride = producerOverride;
    return this;
  }

  @Override
  public QuotaBucket set(String fieldName, Object value) {
    return (QuotaBucket) super.set(fieldName, value);
  }

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

}


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

package org.xito.dcf;

import java.io.*;
import java.awt.*;
import java.beans.*;
import java.awt.datatransfer.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;

import org.w3c.dom.*;
import org.xito.dcf.dnd.*;
import org.xito.blx.*;
import org.xito.dcf.property.*;

/**
 *
 *
 * @author  $Author: drichan $
 * @version $Revision: 1.7 $
 * @since   $Date: 2008/03/28 05:25:57 $
 */
public class DCTile extends DCComponent implements Cloneable, Serializable {

   public static final String TILE_MIME_TYPE = "text/xml";
   public static final String TILE_FLAVOR_NAME = "tile.xml";
   public static final String TILE_REF_FLAVOR_NAME = "tile.ref";
   public static BLXDataFlavor TILE_FLAVOR = new BLXDataFlavor(TILE_MIME_TYPE, TILE_FLAVOR_NAME);
   public static BLXDataFlavor TILE_REF_FLAVOR = new BLXDataFlavor(DCTile.class, TILE_REF_FLAVOR_NAME);

   /**
    */
   public final static Dimension DEFAULT_TILE_SIZE = new Dimension(48,48);
   /**
    */
   public final static Dimension DEFAULT_ICON_SIZE = new Dimension(48,48);

   /**
    */
   public final static String DEFAULT_BKG = "/org/xito/dcf/images/tile_background.gif";

   /**
    */
   public final static String DEFAULT_ICON = "/org/xito/dcf/images/globe_32x32.png";

   /**
    * Resource used to show the Tile is Busy
    */
   public final static String DEFAULT_BUSY = "/org/xito/dcf/images/tile_busy.gif";

   /**
    */
   protected transient static ImageIcon defaultIcon = new ImageIcon(DCTile.class.getResource(DEFAULT_ICON));

   /**
    * Icon used to show Tile is Busy
    */
   protected transient ImageIcon busyIcon;

   /**
    */
   protected final float default_shortTitle_Size = 10f;
   /**
    */
   protected final Font default_shortTitleFont = new Font("SansSerif",Font.PLAIN, 10);
   /**
    */
   public final static String SHOW_TITLE_ATTR = "showtitle";
   /**
    */
   public final static String TITLE_ATTR = "title";
   /**
    */
   public final static String NAME_ATTR = "name";
   /**
    */
   public final static String DESC_ATTR = "desc";
   /**
    */
   public final static String NODE_NAME = "tile";

   /**
    */
   protected boolean showTitle_flag = false;

   /**
    */
   protected boolean showBkgrd_flag = true;

   /**
    */
   protected transient boolean compute_titleFont_flag = true;

   /**
    */
   protected transient Image backgroundImage;

   /**
    * Set to true when we are trying to perform the associated Action
    */
   protected transient boolean showBusy_flag = false;

   /**
    */
   protected Icon icon;
   protected int iconX = 0;
   protected int iconY = 0;
   /**
    */
   protected String shortTitle;
   /**
    */
   protected String title;
   /**
    */
   protected String description;
   /**
    */
   protected transient TitleComponent titleComp;
   /**
    */
   protected Action action;
   /**
    */
   protected transient Font shortTitleFont = default_shortTitleFont;
   /**
    */
   protected transient int shortTitleX = 0;

   protected transient DCPopupMenu tileMenu;
   protected transient MyMenuListener menuListener;
   protected transient JMenuItem propertiesMI;
   protected transient JMenuItem deleteMI;

   /**
    * Create a Tile
    */
   public DCTile() {
      this((Icon)null, null, null, null);
   }

   /**
    * Create a Tile
    * @param pIcon Icon to Use for Tile
    * @param pShortTitle short title for Tile
    * @param pTitle Title for Tile
    * @param pDesc Description of Tile
    */
   public DCTile(Icon pIcon, String pShortTitle, String pTitle, String pDesc) {
      //Call Super for Component Stuff
      super();

      //Size and Location
      setSize(DEFAULT_TILE_SIZE);
      setLayout(null);
      setLocation(0,0);

      //Background
      backgroundImage = (new ImageIcon(DCTile.class.getResource(DEFAULT_BKG))).getImage();
      busyIcon = new ImageIcon(DCTile.class.getResource(DEFAULT_BUSY));

      //Title, Icon
      setShortTitle(pShortTitle);
      setTitle(pTitle);
      setDescription(pDesc);
      setIcon(pIcon);

      //Setup Draggable
      setDraggable(true);
      setTransferable(new MyTransferable(this));

      addMouseListener(new MouseAdapter(){
         public void mouseClicked(MouseEvent pEvent) {
            int _count = pEvent.getClickCount();
            if(SwingUtilities.isLeftMouseButton(pEvent) && _count==2) {
               if(action != null) fireAction();
               return;
            }
            if(SwingUtilities.isRightMouseButton(pEvent) && _count==1) {
               tileMenu.show(pEvent.getComponent(), pEvent.getX(), pEvent.getY());
               return;
            }
         }
      });

      //Setup Menu
      tileMenu = new DCPopupMenu();
      menuListener = new MyMenuListener();
      propertiesMI = new JMenuItem("Properties");
      propertiesMI.addActionListener(menuListener);
      deleteMI = new JMenuItem("Delete");
      deleteMI.addActionListener(menuListener);
      tileMenu.add(propertiesMI);
      tileMenu.add(deleteMI);
   }

   /**
    * Fire the Action Associated with this Tile
    */
   private synchronized void fireAction() {

      if(action == null || showBusy_flag) return;

      //Start a Thread for this Action
      Thread _t = new Thread(new Runnable(){
         public void run() {
            showBusy_flag = true;
            //Repaint the Tile
            invalidate();
            repaint();

            action.actionPerformed(new ActionEvent(this, 0, ""));
            showBusy_flag = false;

            //Repaint the Tile
            invalidate();
            repaint();
         }
      });

      try {
         _t.start();
      }
      catch(Exception e) {
         e.printStackTrace();
      }
   }

   /**
    * Clone this Tile
    * For the tile to be cloned the Action must also be able to clone
    */
   public Object clone() throws CloneNotSupportedException {
      DCTile copy = new DCTile(icon, shortTitle, title, description);
      return copy;
   }

   /**
    * Set the Icon for the Tile
    * @param pIcon to use
    */
   public void setIcon(Icon pIcon) {
      //Setup Icon
      icon = (pIcon == null)?defaultIcon:pIcon;
      //icon.setSize(DEFAULT_ICON_SIZE);
      iconX = (DEFAULT_TILE_SIZE.width/2) - (icon.getIconWidth()/2);
      iconY = 4;

      //Update Action
      if(this.action != null) {
         this.action.putValue("LargeIcon", icon);
      }
   }

   /**
    * Set the Action for the Tile
    * @param pAction
    */
   public void setAction(Action pAction) {
      action = pAction;

      //Setup Properties
      if(action != null) {

         //Setup Icon
         if(icon == null || icon == defaultIcon) {
            setIcon((Icon)action.getValue("LargeIcon"));
         }

         //Setup Titles
         setShortTitle((String)action.getValue(Action.NAME));
         setTitle((String)action.getValue(Action.SHORT_DESCRIPTION));

         action.addPropertyChangeListener(new PropertyChangeListener(){
            public void propertyChange(PropertyChangeEvent evt) {
               String propName = evt.getPropertyName();
               if(propName.equals(Action.NAME)) setShortTitle((String)evt.getNewValue());
               if(propName.equals(Action.SHORT_DESCRIPTION)) setTitle((String)evt.getNewValue());
               if(propName.equals(Action.LONG_DESCRIPTION)) setDescription((String)evt.getNewValue());

               //Tile is Dirty
               setIsDirty(true);

               //Repaint the Tile
               revalidate();
               repaint();
            }
         });
      }

      //Update Transferable
      MyTransferable transferObj = new MyTransferable(this);
      setTransferable(transferObj);
   }

   /**
    * Get the Action of the Tile
    * @return Action
    */
   public Action getAction() {
      return action;
   }

   /**
    * Set the Location of the Tile
    * @param x location
    * @param y location
    */
   public void setLocation(int x, int y) {
      super.setLocation(x, y);

      //Show Title
      if(getShowTitle() && title != null) updateTitleLocation();
   }

   /**
    * Update the Location of the Title based on the Tile Location
    */
   protected void updateTitleLocation() {

      System.out.println("Update Title Location:"+title);
      if(title != null || shortTitle != null) {
         Point _loc = this.getLocation();
         _loc.x = _loc.x - ((titleComp.getWidth() - this.getWidth())/2);
         _loc.x = (_loc.x>0)?_loc.x:0;
         titleComp.setLocation(_loc.x, _loc.y + getHeight());
         titleComp.setVisible(showTitle_flag);
      }
      else if(title == null && shortTitle == null) {
         titleComp.setVisible(false);
      }

      revalidate();
      repaint();
   }

   /**
    * Return the Preferred Size of this Tile
    */
   public Dimension getPreferredSize() {
      return DEFAULT_TILE_SIZE;
   }

   /**
    * Show or Hide the Tile
    * @param pVisible
    */
   public void setVisible(boolean pVisible) {
      super.setVisible(pVisible);

      //Show the Title

      if(showTitle_flag && title != null) {
         updateTitleLocation();
         titleComp.setVisible(pVisible);
      }
   }

   /**
    * Set Tile on Desktop
    * @param pBool
    */
   public void setOnDesktop(boolean pBool) {
      super.setOnDesktop(pBool);
      setShowTitle(pBool);
      titleComp.setOnDesktop(pBool);
   }

   /**
    * Show the Title
    * @param pShowTitle
    */
   public void setShowTitle(boolean pShowTitle) {
      showTitle_flag = pShowTitle;
      if(title != null) updateTitleLocation();
   }

   /**
    * Show the Tile BackGround
    */
   public void setShowBackground(boolean b) {
      showBkgrd_flag = b;
      setOpaque(showBkgrd_flag);
      revalidate();
      repaint();
   }

   /**
    * Do we show the Background
    */
   public boolean getShowBackground() {
      return showBkgrd_flag;
   }

   /**
    * Show the Title
    */
   public boolean getShowTitle() {
      return showTitle_flag;
   }

   /**
    * Set the Short Title. The Short Title is displayed on the Tile itself
    * @param @pTitle
    */
   public void setShortTitle(String pTitle) {

      if(pTitle == null || pTitle.length()==0) {
         shortTitle = null;
      }
      else {
         shortTitle = pTitle;
      }

      compute_titleFont_flag = true;

      //Use the Short Title for the Title if not already Set
      if(title == null && titleComp == null) {
         titleComp = new TitleComponent(shortTitle);
      }
      else if(title==null) {
         titleComp.setText(shortTitle);
      }

      if(title != null || shortTitle != null) updateTitleLocation();

      revalidate();
      repaint();
   }

   /**
    * Get the Short Title
    * @return Short Title
    */
   public String getShortTitle() {
      return shortTitle;
   }

   /**
    * Set the Title of the Tile
    * The Title displays in a seperate Window below the Tile
    * @param pTitle
    */
   public void setTitle(String pTitle) {

      if(pTitle != null) pTitle = pTitle.trim();

      //Can't be empty string
      if(pTitle == null || pTitle.length()==0){
         title = null;
      }
      else {
         title = pTitle;
      }

      //Setup Tooltip
      setToolTipText(title);

      if(titleComp == null) titleComp = new TitleComponent(title);

      titleComp.setText(title == null?shortTitle:title);
      if(title != null || shortTitle != null) updateTitleLocation();
   }

   /**
    * Get the Title
    * @return title
    */
   public String getTitle() {
      return title;
   }

   /**
    * Set the Description of the Tile.
    * The Description is used for the ToolTip
    * @param pDesc
    */
   public void setDescription(String pDesc) {
      description = pDesc;
   }

   /**
    * Get Description
    * @return Description
    */
   public String getDescription() {
      return description;
   }

   /**
    * Show the Busy Icon
    */
   public void showBusy() {
      showBusy_flag = true;
   }

   /**
    * Hide the Busy Icon
    */
   public void hideBusy() {
      showBusy_flag = false;
   }

   /**
    * Paint the Tile Component
    * This method first paints the Background Image then the Icon
    * and then the Title
    */
   public void paintComponent(Graphics pGraphics) {
      super.paintComponent(pGraphics);

      //Anti-Alias Fonts
      //((Graphics2D)pGraphics).addRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));

      //Show Busy if Firing Action
      if(showBusy_flag) {
         busyIcon.paintIcon(this, pGraphics, 0, 0);
         return;
      }

      //Paint BackGround
      if(showBkgrd_flag || this.isOnDesktop()) pGraphics.drawImage(backgroundImage,0,0,null);

      //Paint the Icon
      icon.paintIcon(this, pGraphics, iconX , iconY);

      //Pick a Title to Use.
      String _title;
      if(getShortTitle() == null || getShortTitle().length()==0) {
         _title = getTitle();
      }
      else {
         _title = getShortTitle();
      }

      //Figure out the best font if haven't already
      if(compute_titleFont_flag && _title != null) {
         FontMetrics _fm = pGraphics.getFontMetrics(default_shortTitleFont);
         int _w = SwingUtilities.computeStringWidth(_fm, _title);

         //Get the right Font
         int max_w = getWidth()-5;
         if(_w > max_w) {
            float _dif = (_w - max_w) > 0 ?_w - max_w :0;
            float _ratio = 1 - (_dif/max_w);

            shortTitleFont = default_shortTitleFont.deriveFont(default_shortTitle_Size * _ratio);
            _fm = pGraphics.getFontMetrics(shortTitleFont);
            _w = SwingUtilities.computeStringWidth(_fm, _title);
         }
         else {
            shortTitleFont = default_shortTitleFont;
         }

         shortTitleX = (getWidth()/2) - (_w/2);
         compute_titleFont_flag = false;
      }

      //We only paint the Short Title when we are not displaying the Regular Title
      if(showTitle_flag == false && _title != null) {
         pGraphics.setFont(shortTitleFont);
         pGraphics.drawString(_title, shortTitleX, 43);
      }
   }

   /**
    * Dispose of this Tile
    */
   public void dispose() {
      //Dispose Title Also
      if(titleComp != null) {
         titleComp.dispose();
      }

      super.dispose();
   }

   /**
    *
    */
   public void setBLXElement(BLXElement blxElement) {
      //First set the basic Component Stuff
      super.setBLXElement(blxElement);

      //Now get the Tile Stuff.
      Element _tileElement = blxElement.getDataElement();
      //If null then xml data is bad
      if(_tileElement == null) {
         this.dirty_flag = true;
         return;
      }

      //Process Each Child element of the tile Element
      NodeList _children = _tileElement.getChildNodes();
      for(int i=0;i<_children.getLength();i++) {
         Node _child = _children.item(i);
         if(_child.getNodeType() == Node.ELEMENT_NODE) {
            Element _element = (Element)_child;
            processElement(_element);
         }
      }
   }

   /**
    * Process an Embedded Element
    */
   protected void processElement(Element pElement) {
      try {
         //Check for Properties Element
         if(pElement.getNodeName().equals(BLXProperties.PROPERTIES_NODE_NAME)) {
            BLXProperties _properties = new BLXProperties();
            _properties.setXMLElement(pElement);
            processProperties(_properties);
            return;
         }

         //Get the Object from the Component Factory
         BLXCompFactory _compFactory = BLXCompFactory.getInstance();
         Object _obj = _compFactory.getObject(new BLXElement(pElement, relativeURL), null);

         //See if Object is an Action
         if(_obj instanceof Action) {
            this.setAction((Action)_obj);
         }
      }
      catch(ClassNotFoundException _exp) {
         _exp.printStackTrace();
      }
      catch(InstantiationException _exp) {
         _exp.printStackTrace();
      }
      catch(InvalidBLXXMLException _exp) {
         System.err.println("Error: Tile Contains invalid BLX Element");
      }
   }

   /**
    * Process Properties from XML
    * @param pProperties Properties to Process
    */
   protected void processProperties(BLXProperties pProperties) {
      //Get Show Title Property
      this.setShowTitle(pProperties.getPropertyBoolean(SHOW_TITLE_ATTR));
      this.setTitle(pProperties.getPropertyString(TITLE_ATTR));
      this.setShortTitle(pProperties.getPropertyString(NAME_ATTR));
      this.setDescription(pProperties.getPropertyString(DESC_ATTR));
   }

   /**
    * Gets the XML Data for this Tile
    * @return xml Element
    */
   public Element getDataElement() {
      try {
         //Create Tile Element
         Document _doc = createDOMDocument();
         Element _tileElement = _doc.createElement(NODE_NAME);

         //Add Properties
         BLXProperties _properties = new BLXProperties();
         _properties.setPropertyBoolean(this.SHOW_TITLE_ATTR, this.showTitle_flag);
         _properties.setPropertyString(this.TITLE_ATTR, getTitle());
         _properties.setPropertyString(this.NAME_ATTR, getShortTitle());
         _properties.setPropertyString(this.DESC_ATTR, getDescription());
         _tileElement = (Element)appendChild(_doc, _tileElement, _properties.getXMLElement());

         //Add Action
         if(action != null) {
            if(Beans.isInstanceOf(action, BLXObject.class)) {
               Element _actionE = ((BLXObject)action).getBLXElement().getDOMElement();
               _actionE = (Element)appendChild(_doc, _actionE, ((BLXObject)action).getDataElement());
               _tileElement = (Element)appendChild(_doc, _tileElement, _actionE);
            }
            else if(Beans.isInstanceOf(action, Serializable.class)) {
               _tileElement = (Element)appendChild(_doc, _tileElement, new SerializeObjectAdapter((Serializable)action).getBLXElement().getDOMElement());
            }
         }

         return _tileElement;
      }
      catch(ClassCastException _exp) {
         return null;
      }
   }

   /************************************************************
    * This Class is the listener for the Popup Menu
    ************************************************************/
   class MyMenuListener implements ActionListener {

      public MyMenuListener() {

      }

      public void actionPerformed(ActionEvent pEvent) {

         //Delete
         if(pEvent.getSource() == deleteMI) {
            //Need a Confirm Here
            dispose();
            return;
         }

         //Properties
         if(pEvent.getSource() == propertiesMI) {
            PropertySheetDialog _dialog = null;
            if(action == null) {
               _dialog = new PropertySheetDialog(DCTile.this, "Tile Properties");
            }
            else {
               _dialog = new PropertySheetDialog(action, "Tile Properties");
            }
            _dialog.show();
         }
      }
   }

   /************************************************************
    * This Class is used to display the Title of the Tile
    ************************************************************/
   class TitleComponent extends DCComponent {
      JLabel label;
      FontMetrics metrics;

      TitleComponent(String text) {
         super();
         label = new JLabel();
         label.setForeground(Color.WHITE);
         label.setHorizontalAlignment(JLabel.CENTER);
         label.setFont(label.getFont().deriveFont(Font.PLAIN, 10));
         metrics = Toolkit.getDefaultToolkit().getFontMetrics(label.getFont());
         setLayout(new BorderLayout());
         add(label);

         this.setBackground(Color.BLACK);
         this.setBorder(LineBorder.createBlackLineBorder());
         setText(text);
      }

      void setText(String pText) {
         label.setText(pText);

         if(pText != null) {
            int _w = SwingUtilities.computeStringWidth(metrics, pText);
            setSize(_w+10, 20);
         }
         else {
            setSize(0,0);
         }
      }
   }

   /************************************************************
    * This Class is the Transferable Object for the Tile
    ************************************************************/
   class MyTransferable extends DCTransferObject {
      //Create the Transfer Object
      protected MyTransferable(DCTile pTile) {
         super(pTile);

         //Tile DataFlavor
         dataFlavors.add(DCTile.TILE_FLAVOR);

         //Tile Ref DataFlavor
         dataFlavors.add(DCTile.TILE_REF_FLAVOR);

         //Action Data Flavor
         Action action = pTile.getAction();
         if(action != null) {
            dataFlavors.add(BLXDataFlavor.ACTION_FLAVOR);
         }

      }

      /**
       * Get TransferData
       */
      public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {

         //Return Tile Reference
         if(flavor.equals(DCTile.TILE_REF_FLAVOR)) {
            return dataObj;
         }

         //Return XML for Tile
         else if(flavor.equals(DCTile.TILE_FLAVOR)) {
            return super.getTransferData(BLXDataFlavor.XML_FLAVOR);
         }

         return super.getTransferData(flavor);
      }
   }
}