text:
package com.amazonaws.services.alexaforbusiness.model;

import java.io.Serializable;
import javax.annotation.Generated;

import com.amazonaws.AmazonWebServiceRequest;

/**
 *
 * @see AWS API
 *      Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ListTagsRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {

    /**
     *

     * The ARN of the specified resource for which to list tags.
     *

     */
    private String arn;
    /**
     *

     * An optional token returned from a prior request. Use this token for pagination of results from this action. If
     * this parameter is specified, the response includes only results beyond the token, up to the value specified by
     * MaxResults.
     *

     */
    private String nextToken;
    /**
     *

     * The maximum number of results to include in the response. If more results exist than the specified
     * MaxResults value, a token is included in the response so that the remaining results can be
     * retrieved.
     *

     */
    private Integer maxResults;

    /**
     *

     * The ARN of the specified resource for which to list tags.
     *

     *
     * @param arn
     *        The ARN of the specified resource for which to list tags.
     */

    public void setArn(String arn) {
        this.arn = arn;
    }

    /**
     *

     * The ARN of the specified resource for which to list tags.
     *

     *
     * @return The ARN of the specified resource for which to list tags.
     */

    public String getArn() {
        return this.arn;
    }

    /**
     *

     * The ARN of the specified resource for which to list tags.
     *

     *
     * @param arn
     *        The ARN of the specified resource for which to list tags.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ListTagsRequest withArn(String arn) {
        setArn(arn);
        return this;
    }

    /**
     *

     * An optional token returned from a prior request. Use this token for pagination of results from this action. If
     * this parameter is specified, the response includes only results beyond the token, up to the value specified by
     * MaxResults.
     *

     *
     * @param nextToken
     *        An optional token returned from a prior request. Use this token for pagination of results from this
     *        action. If this parameter is specified, the response includes only results beyond the token, up to the
     *        value specified by MaxResults.
     */

    public void setNextToken(String nextToken) {
        this.nextToken = nextToken;
    }

    /**
     *

     * An optional token returned from a prior request. Use this token for pagination of results from this action. If
     * this parameter is specified, the response includes only results beyond the token, up to the value specified by
     * MaxResults.
     *

     *
     * @return An optional token returned from a prior request. Use this token for pagination of results from this
     *         action. If this parameter is specified, the response includes only results beyond the token, up to the
     *         value specified by MaxResults.
     */

    public String getNextToken() {
        return this.nextToken;
    }

    /**
     *

     * An optional token returned from a prior request. Use this token for pagination of results from this action. If
     * this parameter is specified, the response includes only results beyond the token, up to the value specified by
     * MaxResults.
     *

     *
     * @param nextToken
     *        An optional token returned from a prior request. Use this token for pagination of results from this
     *        action. If this parameter is specified, the response includes only results beyond the token, up to the
     *        value specified by MaxResults.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ListTagsRequest withNextToken(String nextToken) {
        setNextToken(nextToken);
        return this;
    }

    /**
     *

     * The maximum number of results to include in the response. If more results exist than the specified
     * MaxResults value, a token is included in the response so that the remaining results can be
     * retrieved.
     *

     *
     * @param maxResults
     *        The maximum number of results to include in the response. If more results exist than the specified
     *        MaxResults value, a token is included in the response so that the remaining results can be
     *        retrieved.
     */

    public void setMaxResults(Integer maxResults) {
        this.maxResults = maxResults;
    }

    /**
     *

     * The maximum number of results to include in the response. If more results exist than the specified
     * MaxResults value, a token is included in the response so that the remaining results can be
     * retrieved.
     *

     *
     * @return The maximum number of results to include in the response. If more results exist than the specified
     *         MaxResults value, a token is included in the response so that the remaining results can be
     *         retrieved.
     */

    public Integer getMaxResults() {
        return this.maxResults;
    }

    /**
     *

     * The maximum number of results to include in the response. If more results exist than the specified
     * MaxResults value, a token is included in the response so that the remaining results can be
     * retrieved.
     *

     *
     * @param maxResults
     *        The maximum number of results to include in the response. If more results exist than the specified
     *        MaxResults value, a token is included in the response so that the remaining results can be
     *        retrieved.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ListTagsRequest withMaxResults(Integer maxResults) {
        setMaxResults(maxResults);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getArn() != null)
            sb.append("Arn: ").append(getArn()).append(",");
        if (getNextToken() != null)
            sb.append("NextToken: ").append(getNextToken()).append(",");
        if (getMaxResults() != null)
            sb.append("MaxResults: ").append(getMaxResults());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof ListTagsRequest == false)
            return false;
        ListTagsRequest other = (ListTagsRequest) obj;
        if (other.getArn() == null ^ this.getArn() == null)
            return false;
        if (other.getArn() != null && other.getArn().equals(this.getArn()) == false)
            return false;
        if (other.getNextToken() == null ^ this.getNextToken() == null)
            return false;
        if (other.getNextToken() != null && other.getNextToken().equals(this.getNextToken()) == false)
            return false;
        if (other.getMaxResults() == null ^ this.getMaxResults() == null)
            return false;
        if (other.getMaxResults() != null && other.getMaxResults().equals(this.getMaxResults()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getArn() == null) ? 0 : getArn().hashCode());
        hashCode = prime * hashCode + ((getNextToken() == null) ? 0 : getNextToken().hashCode());
        hashCode = prime * hashCode + ((getMaxResults() == null) ? 0 : getMaxResults().hashCode());
        return hashCode;
    }

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

}


text:
{% extends "siteTemplate.html" %} {% load staticfiles %}

{% block content %}

<form action="" method="post">{% csrf_token %}

        Video name
        <input type="text" class="form-control" id="title" name="title" placeholder="Video">

        Short disccription of video
        <textarea class="form-control" id="description" name="description"></textarea>

        Video URL (Site name)
        <input type="text" class="form-control" id="URL" name="URL" placeholder="eg. https://www.youtube.com/watch?v=IerO7XihKL0">

    <button class="btn btn-warning">Add video</button>
</form>

{% endblock %}

redpajama_set_name: RedPajamaGithub


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Revis. gen. pl. (Leipzig) 3: 464 (1898)

#### Original name
Agaricus sapidus Schulzer, 1873

### Remarks
null


text:
package net.ssehub.easy.varModel.model.datatypes;

import net.ssehub.easy.varModel.model.IModelVisitor;
import net.ssehub.easy.varModel.model.IvmlKeyWords;
import net.ssehub.easy.varModel.model.ModelElement;
import net.ssehub.easy.varModel.model.datatypes.Operation.ReturnTypeMode;

/**
 * A reference allows the definition of individual configurations of an (external) element for the referencing element.
 * Currently, operations such as assignments are represented as the respective operations of the base type. Actually,
 * this may be confusing / wrong. See {@link net.ssehub.easy.varModel.cst.ConstraintSyntaxTree#inferDatatype()}.
 *
 * @author heiko beck
 * @author Holger Eichelberger
 **/
public class Reference extends CustomDatatype {

    // DO !NOT! touch the // checkstyle: comments!

    // checkstyle: stop declaration order check

    static final DelegatingType DTYPE = new DelegatingType();

    /**
     * This constant represents the common type of all references. Each specific reference type
     * is assignable to this type.
     */
    public static final IDatatype TYPE = DTYPE;

    public static final Operation TYPE_OF = new Operation(MetaType.TYPE, OclKeyWords.TYPE_OF, TYPE);
    public static final Operation EQUALS
        = Operation.createInfixOperator(BooleanType.TYPE, OclKeyWords.EQUALS, TYPE, TYPE);
    public static final Operation UNEQUALS
        = Operation.createInfixOperator(BooleanType.TYPE, OclKeyWords.UNEQUALS, TYPE, TYPE);
    public static final Operation UNEQUALS_ALIAS
        = Operation.createInfixOperator(BooleanType.TYPE, OclKeyWords.UNEQUALS_ALIAS, TYPE, TYPE);
    public static final Operation ASSIGNMENT
        = Operation.createInfixOperator(BooleanType.TYPE, OclKeyWords.ASSIGNMENT, TYPE, TYPE);
    public static final Operation IS_DEFINED = new Operation(BooleanType.TYPE, OclKeyWords.IS_DEFINED, TYPE)
        .markAsAcceptsNull();
    public static final Operation COPY = new Operation(TYPE, ReturnTypeMode.IMMEDIATE_OPERAND,
        OclKeyWords.COPY, TYPE, AnyType.STRING_TYPE);
    public static final Operation REF_BY = new Operation(TYPE, ReturnTypeMode.IMMEDIATE_OPERAND_DEREF,
        IvmlKeyWords.REFBY, TYPE); // internal, not resolvable through IVML as keyword there!

    // checkstyle: resume declaration order check

    static {
        DTYPE.setDelegate(new Reference());
        DTYPE.addOperation(TYPE_OF);
        DTYPE.addOperation(IS_DEFINED);
        DTYPE.addOperation(COPY);
        DTYPE.addOperation(EQUALS);
        DTYPE.addOperation(UNEQUALS);
        DTYPE.addOperation(UNEQUALS_ALIAS);
        DTYPE.addOperation(ASSIGNMENT);
        DTYPE.addOperation(REF_BY);
    }

    private IDatatype type;

    /**
     * Creates the singleton instance for {@link #TYPE}.
     */
    private Reference() {
        this("<Reference>", null, null);
    }

    /**
     * Constructor for the reference.
     * @param name Name of reference
     * @param type the type to refer to
     * @param parent the object, in which this specific one is embedded
     */
    public Reference(String name, IDatatype type, ModelElement parent) {
        super(name, DTYPE, parent);
        this.type = type;
    }

    /**
     * Returns the type this reference is referring to.
     *
     * @return the type
     */
    public IDatatype getType() {
        return type;
    }

    /**
     * Accept method for the visitor.
     *
     * @param visitor The visitor, which should process this model element.
     */
    public void accept(IModelVisitor visitor) {
        visitor.visitReference(this);
    }

    @Override
    public void accept(IDatatypeVisitor visitor) {
        visitor.visitReference(this);
    }

    /**
    * Determines if the data type represented by this
    * object is either the same as, or is a supertype of
    * type.
    *
    * @param type the type being checked
    * @return true if this type is either the same or a
    *   supertype of type, true else
    */
    public boolean isAssignableFrom(IDatatype type) {
        boolean isAssignable = AnyType.TYPE == type;
        if (super.isAssignableFrom(type) && type instanceof Reference) {
            Reference r = (Reference) type;
            if (null == this.type) {
                isAssignable = true; // this is akin to Reference.INSTANCE so everything reference can be assigned
            } else {
                if (null != r.type) {
                    isAssignable = this.type.isAssignableFrom(DerivedDatatype.resolveToBasis(r.type));
                }
            }
        }
        return isAssignable;
    }

    /**
     * Aims at dereference type in case that it is a reference.
     *
     * @param type the type to dereference
     * @return the dereferenced type (or type if type was not a reference)
     */
    public static IDatatype dereference(IDatatype type) {
        // TODO actually I'm not happy about this explicit dereferencing
        IDatatype result;
        if (type instanceof Reference) {
            result = ((Reference) type).getType();
        } else {
            result = type;
        }
        return result;
    }

    /**
     * Dereferences all datatypes in type.
     *
     * @param types the types to be dereferenced
     */
    public static void dereference(IDatatype[] types) {
        if (null != types) {
            for (int p = 0; p < types.length; p++) {
                types[p] = Reference.dereference(types[p]);
            }
        }
    }

    /**
     * Returns whether the given type is a reference with given generic.
     *
     * @param type the type to check
     * @param parameter the parameter type of the expected reference (may also be a more generic type)
     * @return true if type is refTo(generic), false else
     */
    public static boolean isReferenceTo(IDatatype type, IDatatype parameter) {
        return TYPE.isAssignableFrom(type) && parameter.isAssignableFrom(type.getType());
    }

}


text:
#include <stdio.h>
#include <stdlib.h>

typedef struct node {
    int val;
    struct node *next;
} Node;

/* Makes a new node structure.
 *
 * val: value to store in the node.
 * next: pointer to the next node
 *
 * returns: pointer to a new node
 */
Node *make_node(int val, Node *next) {
    Node *node = malloc(sizeof(Node));
    node->val = val;
    node->next = next;
    return node;
}

/* Prints the values in a list.
 *
 * list: pointer to pointer to Node
 */
void print_list(Node **list) {
    Node *current = *list;

    printf("[ ");
    while (current != NULL) {
        printf("%d ", current->val);
        current = current->next;
    }
    printf("]\n");
}

/* Removes and returns the first element of a list.
 *
 * list: pointer to pointer to Node
 *
 * returns: int or -1 if the list is empty
 */
int pop(Node **list) {
    Node* current = *list;
    if (current == NULL){
      return -1;
    }
    int head = current->val;
    **list = *(current->next);

    return head;
}

/* Adds a new element to the beginning of the list.
 *
 * list: pointer to pointer to Node
 * val: value to add
 */
void push(Node **list, int val) {
    Node *new_head = make_node(val, *list);
    *list = new_head;
}

/* Removes the first element with the given value
 *
 * Frees the removed node.
 *
 * list: pointer to pointer to Node
 * val: value to remove
 *
 * returns: number of nodes removed
 */
int remove_by_value(Node **list, int val) {
  Node *current = *list;
  int removed_nodes = 0;

  while (current->next != NULL) {
      if (current->next->val==val) {
          Node* prev_node = (current->next);

          if (current->next->next == NULL) {
              current->next = NULL;
              break;
          } else {
              *(current->next) = *current->next->next;
          }
          removed_nodes++;
          free(prev_node);
      }
      current = current->next;
  }

  return removed_nodes;
}

/* Reverses the elements of the list.
 *
 * Does not allocate or free nodes.
 *
 * list: pointer to pointer to Node
 */
void reverse(Node **list) {
  Node *current = *list;
  Node *back = NULL;
  Node *next = NULL;

  while (current!=NULL) {
    next = current->next;
    current->next = back;
    back = current;
    current = next;
  }
  *list = back;
}

int main() {
    Node *head = make_node(1, NULL);
    head->next = make_node(2, NULL);
    head->next->next = make_node(3, NULL);
    head->next->next->next = make_node(4, NULL);

    Node **list = &head;
    print_list(list);

    int retval = pop(list);
    print_list(list);

    push(list, retval+10);
    print_list(list);

    remove_by_value(list, 3);
    print_list(list);

    remove_by_value(list, 7);
    print_list(list);

    reverse(list);
    print_list(list);
}


text:
/**
 *
 */
package com.aspose.cloud.pdf;

/**
 * @author Mudassir
 *
 */
/// <summary>
/// represents response of a single Pdf Link
/// </summary>
public class PdfLinkResponse extends com.aspose.cloud.common.BaseResponse
{
    public PdfLinkResponse() { }

    private Link link;
    public Link getLink(){return link;}

}


text:
<?xml version="1.0"?>

<resource xmlns="http://www.wyona.org/yanel/1.0"
  name="scheduler"
  namespace="http://www.wyona.org/yanel/resource/1.0.0"
  class="org.wyona.yanel.impl.resources.scheduler.SchedulerResource"
  >
<description>
Scheduler jobs overview per realm
</description>

<rtd>
<!--
  <property name="foo" default-value="bar"/>
-->
</rtd>
</resource>


text:
namespace python = boost::python;

// ------
//
// This one is relatively easy:
//   expose a function with a default argument
//
// ------
int func2(int v1, int plus = 3);
int func2(int v1, int plus) { return v1 + plus; };
BOOST_PYTHON_FUNCTION_OVERLOADS(f2_overloads, func2, 1, 2)

// ------
//
// More complex:
//   expose a templated function with a default argument
//
// ------
template <typename T>
T func(T v1, int plus = 3);

template <typename T>
T func(T v1, int plus) {
  return v1 + plus;
}

int (*f1_int)(int, int = 3) = func;  // gotta love that syntax!
BOOST_PYTHON_FUNCTION_OVERLOADS(f1_int_overloads, f1_int, 1, 2)
float (*f1_float)(float, int = 3) = func;
BOOST_PYTHON_FUNCTION_OVERLOADS(f1_float_overloads, f1_float, 1, 2)

BOOST_PYTHON_MODULE(overloads) {
  python::def("f2", func2, f2_overloads(python::args("v1", "plus")));

  python::def("f1", f1_int, f1_int_overloads(python::args("v1", "plus")));
  python::def("f1", f1_float, f1_float_overloads(python::args("v1", "plus")));
}


text:
@interface PodsDummy_Pods_ARNPageContainer : NSObject
@end
@implementation PodsDummy_Pods_ARNPageContainer
@end


text:
<?xml version="1.0" ?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<link rel="stylesheet" type="text/css" href="../../../scineplex.css">
<title></title>
<link rel="stylesheet" href="../../../Active.css" type="text/css" />
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<link rev="made" href="mailto:" />

NAME

SYNOPSIS

DESCRIPTION

NAME

DBI::Const::GetInfoType - Data describing GetInfo type codes

SYNOPSIS

  use DBI::Const::GetInfoType;

DESCRIPTION

Imports a %GetInfoType hash which maps names for GetInfo Type Codes into their corresponding numeric values. For example:

  $database_version = $dbh->get_info( $GetInfoType{SQL_DBMS_VER} );

The interface to this module is new and nothing beyond what is written here is guaranteed.


text:
name             "teamcity"
maintainer       "Vyacheslav Slinko"
maintainer_email "vyacheslav.slinko@gmail.com"
license          "MIT"
description      "Installs TeamCity CI from JetBrains"
version          "0.2.2"

recipe "teamcity::build_agent", "Install TeamCity build agent"
recipe "teamcity::server", "Install TeamCity server"
recipe "teamcity::default", "Install TeamCity server and build agent"

depends 'apt',   '~> 2.0'
depends 'yum',   '~> 3.0'


text:
#!/usr/bin/python
import pytz
from lxml import html
from datetime import datetime
import urllib
import re
import urlparse
import json

from myutils import *
from constants import *
import logging

class KMReqBug:
    """
    Convert HTML <TR> to KMBug object,
    the index of element depends on the predefined bug query,
    if bug query changes, then index should change too.
    """
    HEADER_IDX  = {
        'number': 2,
        'reportDate': 5,
        'assignee': 6,
        'sev': 7,
        'productId': 10,
        'comp': 11,
        'compVer': 12,
        'release': 13,
        'subject': 14,
        }

    def __init__(self, tagTR):
        tds = tagTR.xpath("child::td")

        # bug number contained in child <a> element
        self.number = tds[KMReqBug.HEADER_IDX['number']].text_content()

        self.reportDate = tds[KMReqBug.HEADER_IDX['reportDate']].text
        self.assignee = tds[KMReqBug.HEADER_IDX['assignee']].text
        self.sev = tds[KMReqBug.HEADER_IDX['sev']].text
        self.productId = tds[KMReqBug.HEADER_IDX['productId']].text
        self.comp = tds[KMReqBug.HEADER_IDX['comp']].text
        self.compVer = tds[KMReqBug.HEADER_IDX['compVer']].text
        self.release = tds[KMReqBug.HEADER_IDX['release']].text
        self.subject = tds[KMReqBug.HEADER_IDX['subject']].text

class BUG:
    def __init__(self, session):
        self.session = session

    def get_exposed_methods(self):
        methods = {
            'get_bugname_via_oid': self.get_bugname_via_oid,
            'get_normal_KRB_report': self.get_normal_KRB_report,
            'get_urgent_KRB_report': self.get_urgent_KRB_report,
            'get_KDB_list': self.get_KDB_list,
            'get_KDB_info': self.get_KDB_info,
        }

        return methods

    def __get_bug_query_url(self, shortUrl):
        """
        Get real redirect URL from customized bug filter(short URL)
        """
        real_url = None
        try:
            redirect_html_page = self.session.net.fetch_url(shortUrl)
            found = re.search(r'window\.location=\"(?P<real_url>.*)\";', redirect_html_page)
            if found:
                real_url = found.group('real_url')
        except Exception,e:
            logging.error("Failed to get real bug query URL because of: %s" % e)
            return None

        try:
            up = urlparse.urlparse(real_url)
            real_url = up.scheme + "://" +  up.netloc + up.path + '?' + urllib.quote(up.query, "=|&|%")
        except Exception,e:
            logging.error("Failed to reassmebly real bug query URL because of: %s" % e)
            return None

        if not real_url:
            logging.error("Real bug query URL is empty")
            return None

        return real_url

    def get_bugname_via_oid(self, oid):
        """
        get bugzilla username via ABC Email ID
        """
        # when search by email, it only need the part before '@'
        search_key = oid.upper().split("@")[0]

        # build search URL
        params = {'P_FULL_EMAIL': search_key}
        params.update(PARAMS_BUG_SEARCH_USER)
        url = URL_BUG_SEARCH_USER + '?' + urllib.urlencode(params)

        # fetch search page
        html_page = self.session.net.fetch_url(url)
        if not html_page:
            return ""

        find_tds = None
        try:
            root = html.fromstring(html_page)
            find_tds = root.xpath("//table[@class='sortable']/tbody[@id='data']/tr[position()=2]/td[position()=2]")
        except Exception as e:
            logging.debug("Error while parsing search result page.")
            return ""

        if not find_tds:
            logging.debug("No matched bug username can be found, %s may not register to bugzilla." % oid)
            return ""

        username = find_tds[0].text
        return username

    def __get_km_req_bugs(self, is_urgent = False):
        url = URL_NORMAL_KM_REQ_BUGS
        if is_urgent:
            url = URL_URGENT_KM_REQ_BUGS

        # try get real redirect URL from customized bug filter
        real_url = None
        try:
            redirect_html_page = self.session.net.fetch_url(url)
            f = open("/tmp/spatd_debug", 'w')
            f.write(redirect_html_page)
            f.close()
            found = re.search(r'window\.location=\"(?P<real_url>.*)\";', redirect_html_page)
            if found:
                real_url = found.group('real_url')
        except Exception,e:
            logging.error("Failed to get real KM request bugs report URL because of: %s" % e)
            return ""

        if not real_url:
            logging.error("Real KM request bugs report URL is empty")
            return ""

        # get km requested bug html report
        html_report = None
        try:
            up = urlparse.urlparse(real_url)
            real_url = up.scheme + "://" +  up.netloc + up.path + '?' + urllib.quote(up.query, "=|&|%")
            html_report = self.session.net.fetch_url(real_url)
        except Exception,e:
            logging.error("Failed to get KM requested bugs report from bug.us.abc.com because of: %s" % e)
            return ""

        # parse and build KMReqBug objects from html report content
        #parsed_html = html.fromstring(html_report)
        #trs = parsed_html.xpath("//table[@id='SummaryTab']/*/tr[position()>1]")
        #for tr in trs:
        #    bug = KMReqBug(tr)
        #    bug_dict[bug.number] = bug

        return html_report

    def get_normal_KRB_report(self):
        return self.__get_km_req_bugs()

    def get_urgent_KRB_report(self):
        return self.__get_km_req_bugs(is_urgent = True)

    def __extract_date(self, s):
         # extract date from audit line
        date_string = None
        expr = re.compile("\d{2}\/\d{2}\/\d{2}")
        founds = expr.findall(s)
        if founds:
            date_string = founds[0]

        return date_string

    def __get_bug_updates(self, bug_no):
        bug_text_url = "https://bug.abccorp.com/pls/bug/webbug_edit.change_line_type?r_rptno=%s" % bug_no
        try:
            bug_text_html = self.session.net.fetch_url(bug_text_url)
            root = html.fromstring(bug_text_html)
            options = root.xpath("//select[@name='linenums']/option")
            lines = [ opt.text for opt in options]
        except Exceptin, e:
            logging.error("Failed to parse bug updates for bug:%s because of:%s" % (bug_no, e))
            return []

        audit_line_numbers = [ lines.index(line) for line in lines if line.startswith("A:") ]

        bug_updates = []
        total_lines = len(lines)
        last_lineno = total_lines - 1
        for cur_audit_lineno in audit_line_numbers:
            # There are three cases when check for following lines after Audit line
            #case 1: [Audit Line] -> content -> [Audit Line]
            #case 2: [Audit Line] -> [Audit Line]
            #case 3: [Audit Line] -> content ->[END]
            #case 4: [Audit Line] ->[END]
            # so logic is:
            # - try to find out the next audit line
            # - if it is not found, then we need extract the text between (next line after current audit line, end of the lines)
            # - if it is found, then we need extract the text between (next line after current audit line, next audit line)
            update = {}
            found_next_audit_line = True
            try:
                next_audit_lineno = audit_line_numbers[audit_line_numbers.index(cur_audit_lineno) + 1]
            except:
                found_next_audit_line = False

            content = ""
            # if we found next audit line
            if found_next_audit_line:
                # if exist some plain text upadate between these two audit line
                if (next_audit_lineno - cur_audit_lineno) > 1:
                    for j in range(cur_audit_lineno+1, next_audit_lineno):
                        content += lines[j]

                    update['tag'] = lines[cur_audit_lineno]
                    update['content'] = content
                # no plain text after current audit line
                else:
                    update['tag'] = lines[cur_audit_lineno]
                    update['content'] = None

                bug_updates.append(update)
            # if we cannot find next audit line
            else:
                # if exist some plain text between (audit_line, END)
                if (cur_audit_lineno + 1) <= last_lineno:
                    for j in range(cur_audit_lineno+1, last_lineno):
                        content += lines[j]

                    update['tag'] = lines[cur_audit_lineno]
                    update['content'] = content
                else:
                    update['tag'] = lines[cur_audit_lineno]
                    update['content'] = None

                bug_updates.append(update)

        return bug_updates

    def __get_search_updates(self, idx_kmdone_update, bug_updates):
        # find the document id near the "KM_DONE" line
        idx_search_base = idx_kmdone_update
        search_scope = 2

        # find the previous two text updates
        prev_updates = bug_updates[:idx_search_base]
        prev_updates.reverse()

        prev_search_updates = []
        for update in prev_updates:
            print "Checking prev update:%s" % update['tag']
            if update['content']:
                prev_search_updates.append(update)

            if len(prev_search_updates) == search_scope:
                break

        # find the next two text updates
        next_updates = bug_updates[idx_search_base+1:]
        next_search_updates = []
        for update in next_updates:
            print "Checking next update:%s" % update['tag']
            if update['content']:
                next_search_updates.append(update)

            if len(next_search_updates) == search_scope:
                break

        # build search list
        return prev_search_updates + next_search_updates

    def __lookup_document_id(self, idx_kmdone_update, bug_updates):
        doc_id = None

        search_updates = self.__get_search_updates(idx_kmdone_update, bug_updates)
        expr = re.compile(r'\d{6,}\.1')
        for u in search_updates:
            # ignore those updates with unpublised tag
            # for document id should be updated in publish status
            #if update['content'].startswith("N: @"):
            #    continue

            founds = expr.findall(u['content'])
            if founds:
                doc_id = founds[0]
                break

        return doc_id

    def get_KDB_info(self, bug_no):
        """
        Get the KM Done Bug info: including following info:
        * bug_no:        Bug Number
        * complete_time: KM_Done complete time
        * doc_id:        New created KM document for this KM_REQ
        """
        bug_updates = self.__get_bug_updates(bug_no)

        idx_kmdone_update = -1
        for update in bug_updates:
            if "->KM_DONE)" in update['tag']:
                idx_kmdone_update = bug_updates.index(update)

        if idx_kmdone_update == -1:
            logging.error("Failed to locate the KM Done update")
            return {}

        kdb_info = {}
        # Parse KM Done complete date
        kdb_info['complete_date'] = self.__extract_date(bug_updates[idx_kmdone_update]['tag'])
        if not kdb_info['complete_date']:
            logging.error("Failed to extract date from KM Done line")
            return {}

        # Parse new created KM document id
        kdb_info['doc_id'] = self.__lookup_document_id(idx_kmdone_update, bug_updates)
        if not kdb_info['doc_id']:
            logging.error("Failed to extract KM Document id")
            return {}

        kdb_info['bug_no'] = bug_no

        return json.dumps(kdb_info)

    def get_KDB_list(self):
        """
        KDB:  abbreviation of 'KM Done Bug'
        Get all KM_Done bugs
        """
        bug_query_url = self.__get_bug_query_url(URL_KM_DONE_BUGS)
        if not bug_query_url:
            logging.error("Failed to get real KM_Done query URL: %s" % e)
            return []

        # get km requested bug html report
        html_KDBs = None
        try:
            html_KDBs = self.session.net.fetch_url(bug_query_url)
        except Exception,e:
            logging.error("Failed to get KM_Done bugs report from bug.us.abc.com because of: %s" % e)
            return []

        kdb_list = []
        try:
            parsed_html = html.fromstring(html_KDBs)
            bug_links = parsed_html.xpath("//table[@id='SummaryTab']/*/tr/td[position()=3]/a")
            for link in bug_links:
                kdb_list.append(link.text)
        except Exception,e:
            logging.error("Failed to get KM_Done bugs report from bug.us.abc.com because of: %s" % e)
            return []

        return kdb_list


text:
A visualization framework for D3.js and SVG. Ships with prebuilt charts and components.

# Preview Notice
This code is currently in active development, but the code base is stabilizing. The API is still
subject to change before a formal release occurs.

# Chart Types
## Bar
* Standard with vertical and horizontal. Has support for positive and negative values.
* Grouped & Stacked with vertical and horizontal.
* Span with vertical and horizontal. Provides base for Waterfall, Gantt, and related charts.

## Line
* Common line chart
* Area chart
* Sparkline

## Scatterplot
* Commmon scatterplot

## Arc
* Pie
* Donut
* Polar Area
* Gauge

## Radar
* Common radar chart

## Icon Array
* Icons from D3 Symbols
* SVG use path from `defs`
* SVG use external file.

## Custom
Use the base classes `Chart`, `AxesChart`, and `PolarChart` to build custom charts that leverage the
options, lifecycle events, and extensions built into Monte. Or extend

## Extensions
Extensions extend the behavior of a chart. Extensions are driven by chart lifecycle events and stay
up-to-date as the chart updates primarily with the `updated` and `boundsUpdated` events though all
events can be bound.

# Extension Types
* Arc: Draws an arbitrary Arc. Useful for arc fills on gauges, multilevel donuts, etc...
* Axis Label Truncate: Limits size of axis tick labels.
* Axis Label Wrap: Wraps labels at a given width.
* Axis Tick Transform: Controls translation, rotation, and other transforms for axis tick lavels.
* Bar Bg: Draws background rectangles on bar charts. Useful for comparing previous values or goals.
* Crosshair: Connects a point to the edges of a chart with reference lines. Helps map points to
specific axes values.
* Grid: Draws a grid that lines up with Axes tick marks.
* Horizontal Lines: Special case of Grid that draws only horizontal lines.
* Label: Creates an arbitrary that can be data bound. Includes features such as "max width" that
will automatically scale font sizes to fit.
* Polar Grid: Creates a series of arcs (in the simplest case circle, but arbitrary angles can be
used) at the specified distances.
* Polar Line: Draws a line based on given inner and outer radii for a particular angle.
* Polar Ticks: Like polar line, but draws a series of lines at a given interval.
* Reference Line: Draws a line given two coordinates and places a corresponding label.
* Selection Rect: Implements the D3 brushing technique for selecting areas of a chart. Can be
restricted to X or Y axes; otherwise XY selection is allowed.
* Vertical Lines: Special case of Grid that draws only vertical lines.

# License
MIT. See LICENSE for details.

# Author
[Yellow Tugboat](http://www.yellowtugboat.com). Copyright © 2016-2017.


text:
Prevent right click events from propagation and menu from creating.

Part of the noToolbelt / noSeed suite.

https://github.com/ishmaelthedestroyer/noSeed
https://github.com/ishmaelthedestroyer/noToolbelt

Find me @IshmaelsAlive.


text:
var TranslationCollection = requireSrc('translations/TranslationCollection');

describe('A TranslationCollection object', function() {
    it('is created correctly without arguments', function() {
        var collection = new TranslationCollection();

        expect(collection.getHeaders()).toEqual({});
        expect(collection.getTranslations()).toEqual({});
    });

    it('returns the correct headers', function() {
        var  headers = {
            foo: 'bar'
        };
        var collection = new TranslationCollection(headers);

        expect(collection.hasHeader('foo')).toBe(true);
        expect(collection.hasHeader('fu')).toBe(false);
        expect(collection.getHeader('foo')).toBe(headers.foo);
        expect(collection.getHeader('fu')).toBeUndefined();
        expect(collection.getHeaders()).toEqual(headers);
    });

    it('returns the correct domains', function() {
        var translations = {
            'foo': ['bar', 'baz']
        };
        var collection = new TranslationCollection(null, translations);

        expect(collection.hasTranslation('foo')).toBe(true);
        expect(collection.hasTranslation('fu')).toBe(false);
        expect(collection.getTranslations('foo')).toEqual(translations.foo);
        expect(collection.getTranslations('fu')).toBeUndefined();
        expect(collection.getTranslations()).toEqual(translations);
    });
});


text:
package com.metl.h2

import com.metl.data._
import com.metl.utils._
import com.metl.persisted._
import com.metl.h2.dbformats._
import java.util.Date

import net.liftweb.mapper._
import net.liftweb.common._

import scala.compat.Platform.EOL
import _root_.net.liftweb.mapper.{DB => _, DefaultConnectionIdentifier => _, Schemifier => _, StandardDBVendor => _, _}
import _root_.java.sql.{Connection, DriverManager}
import java.time.format.DateTimeFormatter
import java.time._

import com.metl.model.Globals
import com.metl.model.Globals._

class H2Interface(config:ServerConfiguration,filename:Option[String],onConversationDetailsUpdated:Conversation=>Unit) extends SqlInterface(config,new StandardDBVendor("org.h2.Driver", filename.map(f => "jdbc:h2:%s;AUTO_SERVER=TRUE".format(f)).getOrElse("jdbc:h2:mem:%s".format(config.name)),Empty,Empty){
  //adding extra db connections - it defaults to 4, with 20 being the maximum
  override def allowTemporaryPoolExpansion = false
  override def maxPoolSize = 500
  override def doNotExpandBeyond = 500
},onConversationDetailsUpdated,500) {
}

class SqlInterface(config:ServerConfiguration,vendor:StandardDBVendor,onConversationDetailsUpdated:Conversation=>Unit,startingPool:Int = 0,maxPoolSize:Int = 0) extends PersistenceInterface(config) with Logger{
  val configName = config.name
  val serializer = new H2Serializer(config)

  override def shutdown = {
    vendor.closeAllConnections_!
    true
  }

  override def isReady = {
    if (!DB.jndiJdbcConnAvailable_?) {
      DB.defineConnectionManager(DefaultConnectionIdentifier, vendor)
    }
    Schemifier.schemify(true,Schemifier.infoF _,
      List(
        H2Ink,
        H2MultiWordText,
        H2Text,
        H2Image,
        H2Video,
        H2DirtyInk,
        H2DirtyText,
        H2DirtyImage,
        H2DirtyVideo,
        H2MoveDelta,
        H2Quiz,
        H2QuizResponse,
        H2Command,
        H2Submission,
        H2Conversation,
        H2Attendance,
        H2File,
        H2VideoStream,
        H2Resource,
        H2ContextualizedResource,
        H2UnhandledCanvasContent,
        H2UnhandledStanza,
        H2UnhandledContent,
        DatabaseVersion,
        H2Theme,
        H2Grade,
        H2NumericGradeValue,
        H2BooleanGradeValue,
        H2TextGradeValue,
        H2ChatMessage,
        H2UndeletedCanvasContent
      ):_*
    )
    // this starts our pool in advance
    Range(0,Math.min(Math.max(startingPool,0),maxPoolSize)).toList.flatMap(ci => {
      val c = vendor.newConnection(DefaultConnectionIdentifier)
      debug("starting connection: %s => %s".format(ci,c))
      c
    }).foreach(c => {
      vendor.releaseConnection(c)
    })

    //database migration script actions go here.  No try/catch, because I want to break if I can't bring it up to an appropriate version.
    DatabaseVersion.find(By(DatabaseVersion.key,"version"),By(DatabaseVersion.scope,"db")).getOrElse({
      DatabaseVersion.create.key("version").scope("db").intValue(-1).save
    })
    DatabaseVersion.find(By(DatabaseVersion.key,"version"),By(DatabaseVersion.scope,"db")).filter(_.intValue.get < 2).map(versionNumber => {
      info("upgrading db to use partialIndexes for mysql limitations (v2)")
      // update the partialIndexes if it's under version 2, and then increment to version 2
      H2Resource.findAllFields(List(H2Resource.id,H2Resource.identity,H2Resource.partialIdentity)).foreach(res => {
        res.partialIdentity(res.identity.get match {
          case null => ""
          case other => other.take(H2Constants.identity)
        }).save
      })
      H2File.findAllFields(List(H2File.id,H2File.identity,H2File.partialIdentity)).foreach(file => {
        file.partialIdentity(file.identity.get match {
          case null => ""
          case other => other.take(H2Constants.identity)
        }).save
      })
      versionNumber.intValue(2).save
      info("upgraded db to use partialIndexes for mysql limitations (v2)")
      versionNumber
    }).foreach(versionNumber => info("using dbSchema version: %s".format(versionNumber.intValue.get)))
    DatabaseVersion.find(By(DatabaseVersion.key,"version"),By(DatabaseVersion.scope,"db")).filter(_.intValue.get < 4).map(versionNumber => {
      info("upgrading db to switch conversation creation from strings to longs (v3)")
      val dateFormats = List(
        new java.text.SimpleDateFormat("dd/MM/yyyy h:mm:ss a"), // I think this is a C# date format -- "dd/MM/yyyy  22/05/2016 1:27:47 AM.  Of course, it misses the original timezone, so let's hope that it doesn't adjust it too badly.
        new java.text.SimpleDateFormat("EEE MMM dd kk:mm:ss z yyyy") // this is the standard java format, which is what we've been using.
      )
      H2Conversation.findAllFields(List(H2Conversation.id,H2Conversation.created,H2Conversation.creation,H2Conversation.lastAccessed)).foreach(conv => {
        if (conv.creation.get == null || conv.creation.get < 1){
          var result = conv.lastAccessed.get
          val creationString = conv.created.get
          dateFormats.foreach(df => {
            try {
              result = df.parse(creationString).getTime()
            } catch {
              case e:Exception => {}
            }
          })
          conv.creation(result).save
        }
      })
      versionNumber.intValue(4).save
      info("upgraded db to switch conversation creation from strings to longs (v3)")
      versionNumber
    }).foreach(versionNumber => info("using dbSchema version: %s".format(versionNumber.intValue.get)))
    DatabaseVersion.find(By(DatabaseVersion.key,"version"),By(DatabaseVersion.scope,"db")).filter(_.intValue.get < 5).map(versionNumber => {
      info("upgrading db to use room to position themes, not location, because room is indexed")
      H2Theme.findAll.foreach(theme => {
        if (theme.room.get == null){
          theme.room(theme.location.get).save
        }
      })
      versionNumber.intValue(5).save
      info("upgraded db to use room to position themes, which is indexed, where location wasn't.")
      versionNumber
    }).foreach(versionNumber => info("using dbSchema version: %s".format(versionNumber.intValue.get)))
    DatabaseVersion.find(By(DatabaseVersion.key,"version"),By(DatabaseVersion.scope,"db")).filter(_.intValue.get < 6).map(versionNumber => {
      info("upgrading db to hold a copy of the mockdata")
      val mockRoom = "mock|data"
      H2Image.findAll(By(H2Image.room,mockRoom)).foreach(i => {
        val id = i.source.get
        H2Resource.find(By(H2Resource.partialIdentity,id.take(H2Constants.identity)),By(H2Resource.identity,id)).foreach(r => {
          r.delete_!
        })
        i.delete_!
      })
      H2Ink.findAll(By(H2Ink.room,mockRoom)).foreach(_.delete_!)
      H2MultiWordText.findAll(By(H2MultiWordText.room,mockRoom)).foreach(_.delete_!)
      H2MoveDelta.findAll(By(H2MoveDelta.room,mockRoom)).foreach(_.delete_!)
      val h = MockData.mockHistoryValue(config)
      val getId = {
        var innerId = 0
        () => {
          innerId += 1
          innerId
        }
      }
      h.getAll.foreach{
        case i:MeTLImage => {
          i.imageBytes.foreach(bytes => {
            val id = config.postResource(mockRoom,"mock_imageResource_%s".format(getId()),bytes)
            H2Resource.find(By(H2Resource.partialIdentity,id.take(H2Constants.identity)),By(H2Resource.identity,id)).foreach(r => {
              val newImageStanza = i.copy(source = Full(id))
              val foundBytes = config.getResource(id)
              storeStanza(mockRoom,newImageStanza)
            })
          })
        }
        case s:MeTLStanza => storeStanza(h.jid,s)
      }
      versionNumber.intValue(6).save
      info("upgraded db to hold a copy of the mockdata")
      versionNumber
    }).foreach(versionNumber => info("using dbSchema version: %s".format(versionNumber.intValue.get)))
    DatabaseVersion.find(By(DatabaseVersion.key,"version"),By(DatabaseVersion.scope,"db")).filter(_.intValue.get < 7).map(versionNumber => {
      info("upgrading db to set all slides to exposed, because they were previously defaulting to false and we didn't mean that.")
      H2Conversation.findAll.foreach(conv => {
        conv.slides(serializer.slidesToString(serializer.slidesFromString(conv.slides.get).map(_.copy(exposed = true)))).save
      })
      versionNumber.intValue(7).save
      info("upgraded db to set all slides to exposed, because they were previously defaulting to false and we didn't mean that.")
      versionNumber
    }).foreach(versionNumber => info("using dbSchema version: %s".format(versionNumber.intValue.get)))
    DatabaseVersion.find(By(DatabaseVersion.key,"version"),By(DatabaseVersion.scope,"db")).filter(_.intValue.get < 8).map(versionNumber => {
      info("upgrading db to set all future conversation-created dates to 1/7/2016, because they were created by erroneous C# clients and are being reset to the data origin date.")
      val defaultZoneId = ZoneId.of("America/New_York")
      // Origin date is 1 July 2016
      val zonedDateTime = ZonedDateTime.of(LocalDate.of(2016,7,1),LocalTime.of(0,0),defaultZoneId)
      val originDateString = zonedDateTime.format(DateTimeFormatter.ofPattern("EEE MMM dd kk:mm:ss z yyyy"))
      val originDateLong = Instant.from(zonedDateTime).toEpochMilli
      val nowPlusADay = Instant.from(ZonedDateTime.now(defaultZoneId).plusDays(1)).toEpochMilli
      val futureConversationCreateds = H2Conversation.findAll.filter(_.creation > nowPlusADay)
      trace("found %s future conversation createds".format(futureConversationCreateds.length))
      futureConversationCreateds.foreach(h2Conv => {
        trace("updating %s created to %s".format(h2Conv.jid,originDateString))
        h2Conv.created(originDateString).save
        h2Conv.creation(originDateLong).save
      })
      val futureConversationLastAccesseds = H2Conversation.findAll.filter(_.lastAccessed > nowPlusADay)
      trace("found %s future conversation last accesseds".format(futureConversationLastAccesseds.length))
      futureConversationLastAccesseds.foreach(h2Conv => {
        trace("updating %s last accessed to %s".format(h2Conv.jid,originDateString))
        h2Conv.lastAccessed(originDateLong).save
      })
      versionNumber.intValue(8).save
      info("upgraded db to set all future conversation-created dates to 1/7/2016, because they were created by erroneous C# clients and are being reset to the data origin date.")
      versionNumber
    }).foreach(versionNumber => info("using dbSchema version: %s".format(versionNumber.intValue.get)))
    true
  }
  type H2Object = Object
  val RESOURCES = "resource"
  val CONVERSATIONS = "conversation"
  val INKS = "ink"
  val TEXTS = "text"
  val MULTITEXTS = "multiWordText"
  val IMAGES = "image"
  val DIRTYINKS = "dirtyInk"
  val DIRTYTEXTS = "dirtyText"
  val DIRTYIMAGES = "dirtyImage"
  val MOVEDELTAS = "moveDelta"
  val SUBMISSIONS = "submission"
  val QUIZZES = "quiz"
  val QUIZRESPONSES = "quizResponse"
  val ATTENDANCES = "attendance"
  val COMMANDS = "command"

  //stanzas table
  def storeStanza[A <: MeTLStanza](jid:String,stanza:A):Option[A] = Stopwatch.time("H2Interface.storeStanza",{
    val transformedStanza:Option[_ <: H2MeTLStanza[_]] = stanza match {
      case s:MeTLStanza if s.isInstanceOf[Attendance] => Some(serializer.fromMeTLAttendance(s.asInstanceOf[Attendance]).room(jid))
      case s:Attendance => Some(serializer.fromMeTLAttendance(s).room(jid)) // for some reason, it just can't make these match
      case s:MeTLStanza if s.isInstanceOf[MeTLTheme] => Some(serializer.fromTheme(s.asInstanceOf[MeTLTheme]).room(jid))
      case s:MeTLTheme => Some(serializer.fromTheme(s).room(jid))
      case s:MeTLChatMessage => Some(serializer.fromChatMessage(s).room(jid))
      case s:MeTLInk => Some(serializer.fromMeTLInk(s).room(jid))
      case s:MeTLMultiWordText => Some(serializer.fromMeTLMultiWordText(s).room(jid))
      case s:MeTLText => Some(serializer.fromMeTLText(s).room(jid))
      case s:MeTLImage => Some(serializer.fromMeTLImage(s).room(jid))
      case s:MeTLVideo => Some(serializer.fromMeTLVideo(s).room(jid))
      case s:MeTLDirtyInk => Some(serializer.fromMeTLDirtyInk(s).room(jid))
      case s:MeTLDirtyText => Some(serializer.fromMeTLDirtyText(s).room(jid))
      case s:MeTLDirtyImage => Some(serializer.fromMeTLDirtyImage(s).room(jid))
      case s:MeTLDirtyVideo => Some(serializer.fromMeTLDirtyVideo(s).room(jid))
      case s:MeTLCommand => Some(serializer.fromMeTLCommand(s).room(jid))
      case s:MeTLQuiz => Some(serializer.fromMeTLQuiz(s).room(jid))
      case s:MeTLQuizResponse => Some(serializer.fromMeTLQuizResponse(s).room(jid))
      case s:MeTLSubmission => Some(serializer.fromSubmission(s).room(jid))
      case s:MeTLMoveDelta => Some(serializer.fromMeTLMoveDelta(s).room(jid))
      case s:MeTLFile => Some(serializer.fromMeTLFile(s).room(jid))
      case s:MeTLVideoStream => Some(serializer.fromMeTLVideoStream(s).room(jid))
      case s:MeTLGrade => Some(serializer.fromGrade(s).room(jid))
      case s:MeTLNumericGradeValue => Some(serializer.fromNumericGradeValue(s).room(jid))
      case s:MeTLBooleanGradeValue => Some(serializer.fromBooleanGradeValue(s).room(jid))
      case s:MeTLTextGradeValue => Some(serializer.fromTextGradeValue(s).room(jid))
      case s:MeTLUndeletedCanvasContent => Some(serializer.fromMeTLUndeletedCanvasContent(s).room(jid))
      case s:MeTLUnhandledStanza => Some(serializer.fromMeTLUnhandledStanza(s).room(jid))
      case s:MeTLUnhandledCanvasContent => Some(serializer.fromMeTLUnhandledCanvasContent(s).room(jid))
      case other => {
        warn("didn't know how to transform stanza: %s, %s".format(other,other.getClass))
        None
      }
    }
    transformedStanza match {
      case Some(s) => {
        if (s.save){
          Some(serializer.toMeTLData(s)).flatMap(data => data match {
            case ms:A => Some(ms)
            case _ => None
          })
        } else {
          warn("store in jid %s failed: %s".format(jid,stanza))
          None
        }
      }
      case _ => None
    }
  })
  def newSerialGetHistory(jid:String):History = Stopwatch.time("H2Interface.newSerialGetHistory",{
    val newHistory = History(jid)
    val images = Stopwatch.time("h2.fetch.images",H2Image.findAll(By(H2Image.room,jid)).map(i => (i.source.get,i)).toList )
    val videos = Stopwatch.time("h2.fetch.videos",H2Video.findAll(By(H2Video.room,jid)).map(v => (v.source.get,v)).toList )
    val submissions = Stopwatch.time("h2.fetch.submissions",H2Submission.findAll(By(H2Submission.room,jid)).map(s => (s.url.get,s)).toList )
    val files = Stopwatch.time("h2.fetch.files",H2File.findAll(By(H2File.room,jid)).map(f => (f.url.get,f)).toList )
    val quizzes = Stopwatch.time("h2.fetch.quizzes",H2Quiz.findAll(By(H2Quiz.room,jid)).map(q => (q.url.get,q)).toList )
    val identityList = Stopwatch.time("h2.fetch.resourceIds",(images ::: videos ::: submissions ::: files ::: quizzes ::: submissions).map(_._1.take(H2Constants.identity)))
    val resources = Map(Stopwatch.time("h2.fetch.resources",H2Resource.findAll(ByList(H2Resource.partialIdentity,identityList))).flatMap(r => {
      r.bytes.get match {
        case null => None
        case bytes => Some((r.identity.get,bytes))
      }
    }):_*)
    val inks = Stopwatch.time("h2.fetch.inks",H2Ink.findAll(By(H2Ink.room,jid)))
    val texts = Stopwatch.time("h2.fetch.texts",H2Text.findAll(By(H2Text.room,jid)))
    val themes = Stopwatch.time("h2.fetch.themes",H2Theme.findAll(By(H2Theme.room,jid)))
    val chatMessages = Stopwatch.time("h2.fetch.chatMessages",H2ChatMessage.findAll(By(H2ChatMessage.room,jid)))
    val multiWords = Stopwatch.time("h2.fetch.multiWords",H2MultiWordText.findAll(By(H2MultiWordText.room,jid)))
    val dirtyInks = Stopwatch.time("h2.fetch.dirtyInks",H2DirtyInk.findAll(By(H2DirtyInk.room,jid)))
    val dirtyTexts = Stopwatch.time("h2.fetch.dirtyTexts",H2DirtyText.findAll(By(H2DirtyText.room,jid)))
    val dirtyImgs = Stopwatch.time("h2.fetch.dirtyImages",H2DirtyImage.findAll(By(H2DirtyImage.room,jid)))
    val dirtyVids = Stopwatch.time("h2.fetch.dirtyVideos",H2DirtyVideo.findAll(By(H2DirtyVideo.room,jid)))
    val mds = Stopwatch.time("h2.fetch.moveDeltas",H2MoveDelta.findAll(By(H2MoveDelta.room,jid)))
    val quizResponses = Stopwatch.time("h2.fetch.quizzes",H2QuizResponse.findAll(By(H2QuizResponse.room,jid)))
    val videoStreams = Stopwatch.time("h2.fetch.videoStreams",H2VideoStream.findAll(By(H2VideoStream.room,jid)))
    val attendances = Stopwatch.time("h2.fetch.attendances",H2Attendance.findAll(By(H2Attendance.room,jid)))
    val grades = Stopwatch.time("h2.fetch.grades",H2Grade.findAll(By(H2Grade.room,jid)))
    val numericGradeValues = Stopwatch.time("h2.fetch.numericGradeValues",H2NumericGradeValue.findAll(By(H2NumericGradeValue.room,jid)))
    val booleanGradeValues = Stopwatch.time("h2.fetch.booleanGradeValues",H2BooleanGradeValue.findAll(By(H2BooleanGradeValue.room,jid)))
    val textGradeValues = Stopwatch.time("h2.fetch.textGradeValues",H2TextGradeValue.findAll(By(H2TextGradeValue.room,jid)))
    val comms = Stopwatch.time("h2.fetch.commands",H2Command.findAll(By(H2Command.room,jid)))
    val ccs = Stopwatch.time("h2.fetch.ccs",H2UnhandledCanvasContent.findAll(By(H2UnhandledCanvasContent.room,jid)))
    val undeletedCanvasContents = Stopwatch.time("h2.fetch.undeletedCanvasContents", H2UndeletedCanvasContent.findAll(By(H2UndeletedCanvasContent.room,jid)))
    val unhandled = Stopwatch.time("h2.fetch.stanzas",H2UnhandledStanza.findAll(By(H2UnhandledStanza.room,jid)))

    videos.foreach(s => newHistory.addStanza(serializer.toMeTLVideo(s._2,resources.get(s._1).getOrElse(Array.empty[Byte]))))
    images.foreach(s => newHistory.addStanza(serializer.toMeTLImage(s._2,resources.get(s._1).getOrElse(Array.empty[Byte]))))
    files.foreach(s => newHistory.addStanza(serializer.toMeTLFile(s._2,resources.get(s._1).getOrElse(Array.empty[Byte]))))
    quizzes.foreach(s => newHistory.addStanza(serializer.toMeTLQuiz(s._2,resources.get(s._1).getOrElse(Array.empty[Byte]))))
    submissions.foreach(s => newHistory.addStanza(serializer.toSubmission(s._2,resources.get(s._1).getOrElse(Array.empty[Byte]))))

    inks.foreach(s => newHistory.addStanza(serializer.toMeTLInk(s)))
    texts.foreach(s => newHistory.addStanza(serializer.toMeTLText(s)))
    multiWords.foreach(s => newHistory.addStanza(serializer.toMeTLMultiWordText(s)))

    themes.foreach(s => newHistory.addStanza(serializer.toTheme(s)))
    chatMessages.foreach(s => newHistory.addStanza(serializer.toChatMessage(s)))

    dirtyInks.foreach(s => newHistory.addStanza(serializer.toMeTLDirtyInk(s)))
    dirtyTexts.foreach(s => newHistory.addStanza(serializer.toMeTLDirtyText(s)))
    dirtyImgs.foreach(s => newHistory.addStanza(serializer.toMeTLDirtyImage(s)))
    dirtyVids.foreach(s => newHistory.addStanza(serializer.toMeTLDirtyVideo(s)))
    mds.foreach(s => newHistory.addStanza(serializer.toMeTLMoveDelta(s)))
    quizResponses.foreach(s => newHistory.addStanza(serializer.toMeTLQuizResponse(s)))
    videoStreams.foreach(s => newHistory.addStanza(serializer.toMeTLVideoStream(s)))
    attendances.foreach(s => newHistory.addStanza(serializer.toMeTLAttendance(s)))
    comms.foreach(s => newHistory.addStanza(serializer.toMeTLCommand(s)))
    ccs.foreach(s => newHistory.addStanza(serializer.toMeTLUnhandledCanvasContent(s)))
    unhandled.foreach(s => newHistory.addStanza(serializer.toMeTLUnhandledStanza(s)))

    grades.foreach(s => newHistory.addStanza(serializer.toGrade(s)))
    numericGradeValues.foreach(s => newHistory.addStanza(serializer.toNumericGradeValue(s)))
    booleanGradeValues.foreach(s => newHistory.addStanza(serializer.toBooleanGradeValue(s)))
    textGradeValues.foreach(s => newHistory.addStanza(serializer.toTextGradeValue(s)))

    undeletedCanvasContents.foreach(s => newHistory.addStanza(serializer.toMeTLUndeletedCanvasContent(s)))

    newHistory
  })

  protected val identityPoolTaskSupport = new scala.collection.parallel.ForkJoinTaskSupport(new scala.concurrent.forkjoin.ForkJoinPool(5 * Globals.h2ThreadPoolMultiplier))
  protected val stanzaTaskSupport = new scala.collection.parallel.ForkJoinTaskSupport(new scala.concurrent.forkjoin.ForkJoinPool(15 * Globals.h2ThreadPoolMultiplier))
  def newGetHistory(jid:String):History = Stopwatch.time("H2Interface.newGetHistory",{
    val newHistory = History(jid)
    var moveDeltas:List[MeTLMoveDelta] = Nil
    var parO = List(
      () => {
        var images:List[(String,H2Image)] = Nil
        var videos:List[(String,H2Video)] = Nil
        var submissions:List[(String,H2Submission)] = Nil
        var files:List[(String,H2File)] = Nil
        var quizzes:List[(String,H2Quiz)] = Nil

        val parI = List(
          () => {
            images = H2Image.findAll(By(H2Image.room,jid)).map(i => (i.source.get,i)).toList
            true
          },
          () => {
            videos = H2Video.findAll(By(H2Video.room,jid)).map(v => (v.source.get,v)).toList
            true
          },
          () => {
            submissions = H2Submission.findAll(By(H2Submission.room,jid)).map(s => (s.url.get,s)).toList
            true
          },
          () => {
            files = H2File.findAll(By(H2File.room,jid)).map(f => (f.url.get,f)).toList
            true
          },
          () => {
            quizzes = H2Quiz.findAll(By(H2Quiz.room,jid)).map(q => (q.url.get,q)).toList
            true
          }
        ).par
        parI.tasksupport = identityPoolTaskSupport
        parI.map(f => f()).toList
        val resources = Map(H2Resource.findAll(ByList(H2Resource.partialIdentity,(images ::: videos ::: submissions ::: files ::: quizzes ::: submissions).map(_._1.take(H2Constants.identity)))).flatMap(r => {
          r.bytes.get match {
            case null => None
            case bytes => Some((r.identity.get,bytes))
          }
        }):_*)

        videos.foreach(s => newHistory.addStanza(serializer.toMeTLVideo(s._2,resources.get(s._1).getOrElse(Array.empty[Byte]))))
        images.foreach(s => newHistory.addStanza(serializer.toMeTLImage(s._2,resources.get(s._1).getOrElse(Array.empty[Byte]))))
        files.foreach(s => newHistory.addStanza(serializer.toMeTLFile(s._2,resources.get(s._1).getOrElse(Array.empty[Byte]))))
        quizzes.foreach(s => newHistory.addStanza(serializer.toMeTLQuiz(s._2,resources.get(s._1).getOrElse(Array.empty[Byte]))))
        submissions.foreach(s => newHistory.addStanza(serializer.toSubmission(s._2,resources.get(s._1).getOrElse(Array.empty[Byte]))))
      },
      () => H2Ink.findAll(By(H2Ink.room,jid)).foreach(s => newHistory.addStanza(serializer.toMeTLInk(s))),
      () => H2Text.findAll(By(H2Text.room,jid)).foreach(s => newHistory.addStanza(serializer.toMeTLText(s))),
      () => H2MultiWordText.findAll(By(H2MultiWordText.room,jid)).foreach(s => newHistory.addStanza(serializer.toMeTLMultiWordText(s))),
      () => H2DirtyInk.findAll(By(H2DirtyInk.room,jid)).foreach(s => newHistory.addStanza(serializer.toMeTLDirtyInk(s))),
      () => H2DirtyText.findAll(By(H2DirtyText.room,jid)).foreach(s => newHistory.addStanza(serializer.toMeTLDirtyText(s))),
      () => H2DirtyImage.findAll(By(H2DirtyImage.room,jid)).foreach(s => newHistory.addStanza(serializer.toMeTLDirtyImage(s))),
      () => H2DirtyVideo.findAll(By(H2DirtyVideo.room,jid)).foreach(s => newHistory.addStanza(serializer.toMeTLDirtyVideo(s))),
      () => {
        moveDeltas = H2MoveDelta.findAll(By(H2MoveDelta.room,jid)).map(s => serializer.toMeTLMoveDelta(s))
      },
      () => H2QuizResponse.findAll(By(H2QuizResponse.room,jid)).foreach(s => newHistory.addStanza(serializer.toMeTLQuizResponse(s))),
      () => H2VideoStream.findAll(By(H2VideoStream.room,jid)).toList.par.map(s => newHistory.addStanza(serializer.toMeTLVideoStream(s))).toList,
      () => H2Attendance.findAll(By(H2Attendance.room,jid)).foreach(s => newHistory.addStanza(serializer.toMeTLAttendance(s))),
      () => H2Theme.findAll(By(H2Theme.room,jid)).foreach(s => newHistory.addStanza(serializer.toTheme(s))),
      () => H2ChatMessage.findAll(By(H2ChatMessage.room,jid)).foreach(s => newHistory.addStanza(serializer.toChatMessage(s))),
      () => H2Command.findAll(By(H2Command.room,jid)).foreach(s => newHistory.addStanza(serializer.toMeTLCommand(s))),
      () => H2UndeletedCanvasContent.findAll(By(H2UndeletedCanvasContent.room,jid)).foreach(s => newHistory.addStanza(serializer.toMeTLUndeletedCanvasContent(s))),
      () => H2UnhandledCanvasContent.findAll(By(H2UnhandledCanvasContent.room,jid)).foreach(s => newHistory.addStanza(serializer.toMeTLUnhandledCanvasContent(s))),
      () => H2UnhandledStanza.findAll(By(H2UnhandledStanza.room,jid)).foreach(s => newHistory.addStanza(serializer.toMeTLUnhandledStanza(s))),
      () => H2Grade.findAll(By(H2Grade.room,jid)).foreach(s => newHistory.addStanza(serializer.toGrade(s))),
      () => H2NumericGradeValue.findAll(By(H2NumericGradeValue.room,jid)).foreach(s => newHistory.addStanza(serializer.toNumericGradeValue(s))),
      () => H2BooleanGradeValue.findAll(By(H2BooleanGradeValue.room,jid)).foreach(s => newHistory.addStanza(serializer.toBooleanGradeValue(s))),
      () => H2TextGradeValue.findAll(By(H2TextGradeValue.room,jid)).foreach(s => newHistory.addStanza(serializer.toTextGradeValue(s)))
    ).par
    parO.tasksupport = stanzaTaskSupport
    parO.map(f => f()).toList
    moveDeltas.foreach(s => newHistory.addStanza(s))
    newHistory
  })
  def getHistory(jid:String):History = Stopwatch.time("H2Interface.getHistory",{
    //oldGetHistory(jid)
    newGetHistory(jid)
    //newSerialGetHistory(jid)
  })
  def oldGetHistory(jid:String):History = Stopwatch.time("H2Interface.oldGetHistory",{
    val newHistory = History(jid)
    var moveDeltas:List[MeTLMoveDelta] = Nil
    List(
      () => H2Ink.findAll(By(H2Ink.room,jid)).foreach(s => newHistory.addStanza(serializer.toMeTLInk(s))),
      () => H2Text.findAll(By(H2Text.room,jid)).foreach(s => newHistory.addStanza(serializer.toMeTLText(s))),
      () => H2Theme.findAll(By(H2Theme.room,jid)).foreach(s => newHistory.addStanza(serializer.toTheme(s))),
      () => H2MultiWordText.findAll(By(H2MultiWordText.room,jid)).foreach(s => newHistory.addStanza(serializer.toMeTLMultiWordText(s))),
      () => {
        H2Image.findAll(By(H2Image.room,jid)).toList.par.map(s => {
          newHistory.addStanza(serializer.toMeTLImage(s))
        }).toList
      },
      () => H2Video.findAll(By(H2Video.room,jid)).toList.par.map(s => newHistory.addStanza(serializer.toMeTLVideo(s))).toList,
      () => H2DirtyInk.findAll(By(H2DirtyInk.room,jid)).foreach(s => newHistory.addStanza(serializer.toMeTLDirtyInk(s))),
      () => H2DirtyText.findAll(By(H2DirtyText.room,jid)).foreach(s => newHistory.addStanza(serializer.toMeTLDirtyText(s))),
      () => H2DirtyImage.findAll(By(H2DirtyImage.room,jid)).foreach(s => newHistory.addStanza(serializer.toMeTLDirtyImage(s))),
      () => H2DirtyVideo.findAll(By(H2DirtyVideo.room,jid)).foreach(s => newHistory.addStanza(serializer.toMeTLDirtyVideo(s))),
      () => {
        moveDeltas = H2MoveDelta.findAll(By(H2MoveDelta.room,jid)).map(s => serializer.toMeTLMoveDelta(s))
      },
      () => H2Submission.findAll(By(H2Submission.room,jid)).toList.par.map(s => newHistory.addStanza(serializer.toSubmission(s))).toList,
      () => H2Quiz.findAll(By(H2Quiz.room,jid)).toList.par.map(s => newHistory.addStanza(serializer.toMeTLQuiz(s))).toList,
      () => H2QuizResponse.findAll(By(H2QuizResponse.room,jid)).foreach(s => newHistory.addStanza(serializer.toMeTLQuizResponse(s))),
      () => H2File.findAll(By(H2File.room,jid)).toList.par.map(s => newHistory.addStanza(serializer.toMeTLFile(s))).toList,
      () => H2VideoStream.findAll(By(H2VideoStream.room,jid)).toList.par.map(s => newHistory.addStanza(serializer.toMeTLVideoStream(s))).toList,
      () => H2Attendance.findAll(By(H2Attendance.room,jid)).foreach(s => newHistory.addStanza(serializer.toMeTLAttendance(s))),
      () => H2Theme.findAll(By(H2Theme.room,jid)).foreach(s => newHistory.addStanza(serializer.toTheme(s))),
      () => H2ChatMessage.findAll(By(H2ChatMessage.room,jid)).foreach(s => newHistory.addStanza(serializer.toChatMessage(s))),
      () => H2Command.findAll(By(H2Command.room,jid)).foreach(s => newHistory.addStanza(serializer.toMeTLCommand(s))),
      () => H2UndeletedCanvasContent.findAll(By(H2UndeletedCanvasContent.room,jid)).foreach(s => newHistory.addStanza(serializer.toMeTLUndeletedCanvasContent(s))),
      () => H2UnhandledCanvasContent.findAll(By(H2UnhandledCanvasContent.room,jid)).foreach(s => newHistory.addStanza(serializer.toMeTLUnhandledCanvasContent(s))),
      () => H2UnhandledStanza.findAll(By(H2UnhandledStanza.room,jid)).foreach(s => newHistory.addStanza(serializer.toMeTLUnhandledStanza(s))),
      () => H2Grade.findAll(By(H2Grade.room,jid)).foreach(s => newHistory.addStanza(serializer.toGrade(s))),
      () => H2NumericGradeValue.findAll(By(H2NumericGradeValue.room,jid)).foreach(s => newHistory.addStanza(serializer.toNumericGradeValue(s))),
      () => H2BooleanGradeValue.findAll(By(H2BooleanGradeValue.room,jid)).foreach(s => newHistory.addStanza(serializer.toBooleanGradeValue(s))),
      () => H2TextGradeValue.findAll(By(H2TextGradeValue.room,jid)).foreach(s => newHistory.addStanza(serializer.toTextGradeValue(s)))
    ).par.map(f => f()).toList
  //.toList.foreach(group => group.foreach(gf => gf()))
                              //val unhandledContent = H2UnhandledContent.findAll(By(H2UnhandledContent.room,jid)).map(s => serializer.toMeTLUnhandledData(s))
                              //(inks ::: texts ::: images ::: dirtyInks ::: dirtyTexts ::: dirtyImages ::: moveDeltas ::: quizzes ::: quizResponses ::: commands ::: submissions ::: files ::: attendances ::: unhandledCanvasContent ::: unhandledStanzas /*:: unhandledContent */).foreach(s => newHistory.addStanza(s))
      moveDeltas.foreach(s => newHistory.addStanza(s))
      newHistory
  })

  //conversations table
  protected lazy val mbDef = new MessageBusDefinition("global","conversationUpdating",receiveConversationDetailsUpdated _)
  protected lazy val conversationMessageBus = config.getMessageBus(mbDef)
  protected lazy val conversationCache = scala.collection.mutable.Map(H2Conversation.findAll.map(c => (c.jid.get,serializer.toConversation(c))):_*)
  protected def updateConversation(c:Conversation):Boolean = {
    try {
      conversationCache.update(c.jid,c)
      updateMaxJid
      serializer.fromConversation(c).save
      onConversationDetailsUpdated(c)
      true
    } catch {
      case e:Throwable => {
        error("exception thrown while updating conversation: %s\r\n%s".format(e.getMessage,e.getStackTrace))
        false
      }
    }
  }
  protected def updateMaxJid = maxJid = try {
    conversationCache.values.map(_.jid).max
  } catch {
    case _:Throwable => 0
  }
  protected var maxJid = 0
  protected def getNewJid = synchronized {
    if (maxJid == 0){
      updateMaxJid
    }
    val oldMax = maxJid
    maxJid += 1000
    maxJid
  }
  protected def receiveConversationDetailsUpdated(m:MeTLStanza) = {
    m match {
      case c:MeTLCommand if c.command == "/UPDATE_CONVERSATION_DETAILS" && c.commandParameters.length == 1 => {
        try{
          val jidToUpdate = c.commandParameters(0).toInt
          val conversation = detailsOfConversation(jidToUpdate)
          conversationCache.update(conversation.jid,conversation)
          updateMaxJid
          onConversationDetailsUpdated(conversation)
        } catch {
          case e:Throwable => error("exception while attempting to update conversation details",e)
        }
      }
      case _ => {}
    }
  }
  def getAllConversations:List[Conversation] = conversationCache.values.toList
  def searchForConversation(query:String):List[Conversation] = conversationCache.values.filter(c => c.title.toLowerCase.trim.contains(query.toLowerCase.trim) || c.author.toLowerCase.trim == query.toLowerCase.trim).toList
  def searchForConversationByCourse(courseId:String):List[Conversation] = conversationCache.values.filter(c => c.subject.toLowerCase.trim.equals(courseId.toLowerCase.trim) || c.foreignRelationship.exists(_.key.toLowerCase.trim == courseId.toLowerCase.trim)).toList
  def conversationFor(slide:Int):Int = (slide / 1000 ) * 1000
  def detailsOfConversation(jid:Int):Conversation = conversationCache(jid)
  def createConversation(title:String,author:String):Conversation = {
    val now = new Date()
    val newJid = getNewJid
    val details = Conversation(config,author,now.getTime,List(Slide(config,author,newJid + 1,0)),"unrestricted","",newJid,title,now.getTime,Permissions.default(config))
    updateConversation(details)
    details
  }
  protected def findAndModifyConversation(jidString:String,adjustment:Conversation => Conversation):Conversation  = Stopwatch.time("H2Interface.findAndModifyConversation",{
    try {
      val jid = jidString.toInt
      detailsOfConversation(jid) match {
        case c:Conversation if (c.jid == jid) => {
          val updatedConv = adjustment(c)
          if (updateConversation(updatedConv)){
            updatedConv
          } else {
            Conversation.empty
          }
        }
        case other => other
      }
    } catch {
      case e:Throwable => {
        error("failed to alter conversation",e)
        Conversation.empty
      }
    }
  })
  def deleteConversation(jid:String):Conversation = updateSubjectOfConversation(jid,"deleted")
  def renameConversation(jid:String,newTitle:String):Conversation = findAndModifyConversation(jid,c => c.rename(newTitle))
  def changePermissionsOfConversation(jid:String,newPermissions:Permissions):Conversation = findAndModifyConversation(jid,c => c.replacePermissions(newPermissions))
  def updateSubjectOfConversation(jid:String,newSubject:String):Conversation = findAndModifyConversation(jid,c => c.replaceSubject(newSubject))
  def addSlideAtIndexOfConversation(jid:String,index:Int):Conversation = findAndModifyConversation(jid,c => c.addSlideAtIndex(index))
  def addGroupSlideAtIndexOfConversation(jid:String,index:Int,grouping:GroupSet):Conversation = findAndModifyConversation(jid,c => c.addGroupSlideAtIndex(index,grouping))
  def reorderSlidesOfConversation(jid:String,newSlides:List[Slide]):Conversation = findAndModifyConversation(jid,c => c.replaceSlides(newSlides))
  def updateConversation(jid:String,conversation:Conversation):Conversation = {
    if (jid == conversation.jid.toString){
      updateConversation(conversation)
      conversation
    } else {
      conversation
    }
  }

  //resources table
  def getResource(identity:String):Array[Byte] = Stopwatch.time("H2Interface.getResource",{
    H2Resource.find(By(H2Resource.partialIdentity,identity.take(H2Constants.identity)),By(H2Resource.identity,identity)).map(r => {
      r.bytes.get
    }).openOr({
      Array.empty[Byte]
    })

  })
  def postResource(jid:String,userProposedId:String,data:Array[Byte]):String = Stopwatch.time("H2Interface.postResource",{
    val now = new Date().getTime.toString
    val possibleNewIdentity = "%s:%s:%s".format(jid,userProposedId,now)
    H2Resource.find(By(H2Resource.partialIdentity,possibleNewIdentity.take(H2Constants.identity)),By(H2Resource.identity,possibleNewIdentity)) match {
      case Full(r) => {
        warn("postResource: identityAlready exists for %s".format(userProposedId))
        val newUserProposedIdentity = "%s_%s".format(userProposedId,now)
        postResource(jid,newUserProposedIdentity,data)
      }
      case _ => {
        H2Resource.create.partialIdentity(possibleNewIdentity.take(H2Constants.identity)).identity(possibleNewIdentity).bytes(data).room(jid).save
        trace("postResource: saved %s bytes in %s at %s".format(data.length,jid,possibleNewIdentity))
        possibleNewIdentity
      }
    }
  })
  def getResource(jid:String,identity:String):Array[Byte] = Stopwatch.time("H2Interface.getResource",{
    H2ContextualizedResource.find(
      By(H2ContextualizedResource.context,jid),
      By(H2ContextualizedResource.identity,identity)
    ).map(r => {
      r.bytes.get
    }).openOr({
      Array.empty[Byte]
    })

  })
  def insertResource(jid:String,data:Array[Byte]):String = Stopwatch.time("H2Interface.insertResource",{
    H2ContextualizedResource.create.context(jid).bytes(data).saveMe.identity.get
  })
  def upsertResource(jid:String,identifier:String,data:Array[Byte]):String = Stopwatch.time("H2Interface.upsertResource",{
    H2ContextualizedResource.find(
      By(H2ContextualizedResource.context,jid),
      By(H2ContextualizedResource.identity,identifier)
    ).map(r => {
      r.bytes(data).saveMe.identity.get
    }).openOr({
      insertResource(jid,data)
    })
  })
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<title>rapidjson: Member List</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

rapidjson

A fast JSON parser/generator for C++ with both SAX/DOM style API

Main Page

Related Pages

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Class List

Class Index

Class Hierarchy

Class Members

 All Classes Functions Variables Typedefs Pages

rapidjson

MemoryPoolAllocator

rapidjson::MemoryPoolAllocator< BaseAllocator > Member List

This is the complete list of members for rapidjson::MemoryPoolAllocator< BaseAllocator >, including all inherited members.

Capacity()	rapidjson::MemoryPoolAllocator< BaseAllocator >	inline

Clear()	rapidjson::MemoryPoolAllocator< BaseAllocator >	inline

Free(void *)	rapidjson::MemoryPoolAllocator< BaseAllocator >	inlinestatic

kNeedFree	rapidjson::MemoryPoolAllocator< BaseAllocator >	static

Malloc(size_t size)	rapidjson::MemoryPoolAllocator< BaseAllocator >	inline

MemoryPoolAllocator(size_t chunkSize=kDefaultChunkCapacity, BaseAllocator *baseAllocator=0)	rapidjson::MemoryPoolAllocator< BaseAllocator >	inline

MemoryPoolAllocator(char *buffer, size_t size, size_t chunkSize=kDefaultChunkCapacity, BaseAllocator *baseAllocator=0)	rapidjson::MemoryPoolAllocator< BaseAllocator >	inline

Realloc(void *originalPtr, size_t originalSize, size_t newSize)	rapidjson::MemoryPoolAllocator< BaseAllocator >	inline

Size()	rapidjson::MemoryPoolAllocator< BaseAllocator >	inline

~MemoryPoolAllocator()	rapidjson::MemoryPoolAllocator< BaseAllocator >	inline

<address class="footer">
Generated on Fri Nov 16 2012 21:08:20 for rapidjson by

 1.8.1.2
</address>


text:
package querqy.rewrite.commonrules.select;

import querqy.rewrite.commonrules.model.Instructions;

import java.util.Objects;

public class ExpressionFilterCriterion implements FilterCriterion {

    private final String expression;

    public ExpressionFilterCriterion(final String expression) {
        this.expression = expression;
    }

    @Override
    public boolean isValid(final Instructions instructions) {
        return instructions.getProperties().matches(expression);
    }

    public String getExpression() {
        return expression;
    }

    @Override
    public String toString() {
        return "ExpressionFilterCriterion{" +
                "expression='" + expression + "'}'";
    }

    @Override
    public boolean equals(final Object o) {
        if (this == o) return true;
        if (!(o instanceof ExpressionFilterCriterion)) return false;
        final ExpressionFilterCriterion that = (ExpressionFilterCriterion) o;
        return Objects.equals(expression, that.expression);
    }

    @Override
    public int hashCode() {
        return 811 + expression.hashCode();
    }
}


text:
@interface WXSDKInstance (BMExtend)

-(void)bm_destroyInstance;

- (void)_renderWithMainBundleString:(NSString *)mainBundleString;
- (void)bm__renderWithMainBundleString:(NSString *)mainBundleString;

@end


text:
#ifndef Vxa_VInfiniteSet_Interface
#define Vxa_VInfiniteSet_Interface

/************************
 *****  Components  *****
 ************************/

#include "Vxa_VSet.h"

/**************************
 *****  Declarations  *****
 **************************/

/*************************
 *****  Definitions  *****
 *************************/

namespace Vxa {
    class Vxa_API VInfiniteSet : public VSet {
	DECLARE_CONCRETE_RTTLITE (VInfiniteSet, VSet);

    //  Construction
    public:
	VInfiniteSet ();

    //  Destruction
    protected:
	~VInfiniteSet ();

    //  Cardinality
    private:
	cardinality_t cardinality_() const {
	    return cardinality ();
	}
    public:
	cardinality_t cardinality () const {
	    return ~static_cast<cardinality_t>(0);
	}

    //  Transmission
    protected:
	bool transmitUsing_(VCallType2Exporter *pExporter, VMonotypeMapMaker *pMapMaker, object_reference_array_t const &rInjection);
	bool transmitUsing_(VCallType2Exporter *pExporter, VMonotypeMapMaker *pMapMaker);
    };
}

#endif


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
Ark. Bot. 24A(no. 3): 23 (1931)

#### Original name
Arthopyrenia angermannica Nils.

### Remarks
null


text:
Sick of client javascript modules adding global properties to the ```window``` object?

This [browserify](https://github.com/substack/node-browserify) transform allows
you to pass in a second parameter to ```require()``` which is an array of
properties that the offending object WOULD have set on ```window``` but will
instead return as part of a proper ```module.exports``` object. Joy!

# Installation

Install deglobalify through npm:

```
$ npm install deglobalify
```

# Example

## The old and bad way...

Say you have this bad client module that pollutes the global ```window``` object:

``` js
// /public/scripts/vendor/badmodule.js
window.myfunc = function() { return 42; };
```

You include it in your browserify code:

```
// /public/scripts/app.js
var domready = require('domready') // regular npm module
  , badmodule = require('./vendor/badmodule.js'); // returns undefined

domready(function () {
  console.log(myfunc());        // prints 42 (global alert!)
  console.log(window.myfunc()); // prints 42 (global alert!)
});
```

Because the bad module pollutes the ```window``` object, you need to get access
to the ```myfunc``` function by referencing the window object.

## The better deglobalify way

Once you know what global ```window``` properties the bad module is clobbering,
you can pass it into the ```require``` function as a list of of properties like
so:

``` js
// /public/scripts/app.js
var domready = require('domready') // regular npm module
  , badmodule = require('./vendor/badmodule.js', ['myfunc']); // returns an exports object

var myfunc = badmodule.myfunc; // myfunc is an export and NOT on the global window

domready(function () {
  console.log(myfunc());        // prints 42 (whoohoo!)
  console.log(window.myfunc()); // throws an exception because window.myfunc is undefined
});
```

Then call ```browserify``` using the deglobalify transform:

```
$ browserify -t deglobalify public/scripts/app.js -o public/build/bundle.js
```

Then incude ```bundle.js``` in your HTML and you're done!

The bad module will return a regular commonjs exports object with your requested
properties on it!

And the ```window``` object won't be clobbered, keeping the world a better and
safer place for all :-)

## Using deglobalify with other transforms

If you're using deglobalify with other Browserify transforms such as
[debowerify](https://github.com/eugeneware/debowerify) (which allows you to easily
use [bower](http://bower.io) components with browserify), or
[decomponentify](https://github.com/eugeneware/decomponentify) (which allows you
to use [component](https://github.com/component/component) components with
browserify, then you are generally better to put deglobalify at the end of the
transform chain:

```
$ browserify -t debowerify -t deamdify -t deglobalify public/scripts/app.js -o public/build/bundle.js
```

Enjoy a global variable free existence and get a peaceful night's rest!


text:
pkg_name=clens
pkg_origin=core
pkg_version=0.7.0
pkg_maintainer="The Habitat Maintainers <humans@habitat.sh>"
pkg_description="\
clens is a convenience library to port code to different operating systems. \
Operating systems traditionally have different enough APIs that porting code \
is painful. To keep code readable and #ifdef free, clens brings other APIs or \
missing functions into specific OS focus.\
"
pkg_upstream_url="https://sourceforge.net/projects/clens/"
pkg_license=('isc')
pkg_source="https://downloads.sourceforge.net/project/${pkg_name}/${pkg_name}-${pkg_version}.tar.gz"
pkg_shasum="064ac9954d38633e2cff6b696fd049dedc3e90b79acffbee1a87754bcf604267"
pkg_deps=(
  core/glibc
)
pkg_build_deps=(
  lilian/coreutils
  lilian/diffutils
  lilian/patch
  lilian/make
  lilian/gcc
  lilian/libbsd
)
pkg_include_dirs=(include)
pkg_lib_dirs=(lib)

source ../defaults.sh

do_build() {
  mkdir -pv obj
  make -j"$(nproc)" LOCALBASE=$pkg_prefix
}

do_install() {
  make -j"$(nproc)" LOCALBASE=$pkg_prefix install
}

# ----------------------------------------------------------------------------
# **NOTICE:** What follows are implementation details required for building a
# first-pass, "stage1" toolchain and environment. It is only used when running
# in a "stage1" Studio and can be safely ignored by almost everyone. Having
# said that, it performs a vital bootstrapping process and cannot be removed or
# significantly altered. Thank you!
# ----------------------------------------------------------------------------
if [[ "$STUDIO_TYPE" = "stage1" ]]; then
  pkg_build_deps=(
    lilian/gcc/7.1.0/20170624225400
    lilian/coreutils/8.27/20170624233515
    lilian/diffutils/3.6/20170624234540
    lilian/make/4.2.1/20170624234911
    lilian/patch/2.7.5/20170624234926
    lilian/libbsd/0.8.3/20170626203458
  )
fi


text:
package org.tud.inf.st.mbt.ulang.guigraph;

import org.eclipse.draw2d.ColorConstants;
import org.eclipse.draw2d.Ellipse;
import org.eclipse.draw2d.RotatableDecoration;
import org.eclipse.draw2d.geometry.Point;
import org.eclipse.draw2d.geometry.Rectangle;

public class EllipseDecoration extends Ellipse implements RotatableDecoration {

	public EllipseDecoration() {
		setSize(14, 14);
		setFill(true);
		setBackgroundColor(ColorConstants.red);
	}

	@Override
	public void setBounds(Rectangle rect) {
		super.setBounds(new Rectangle(rect.x - 7, rect.y - 7, rect.width,
				rect.height));
	}

	public void setReferencePoint(Point p) {

	}
}


text:
"""
Created on Thu Sep 21 17:20:38 2017

@author: christopherbridge
"""

import numpy as np

from .materials import Materials

class Pipe(object):
    """
    Pipe object
    Store the outer diameter, wall thickness and material properties
    determine all other properties

    Note, units are SI. Options for Imperial units may follow

    """
    def __init__(self, outer_diameter=-1, wall_thickness=-1, material='default'):
        """
        Initialise the pipe with outer diameter, wall thickness and a
        default material
        """
        self._diameter_outer = outer_diameter
        self._wall_thickness = wall_thickness
        self._material_name = material
        #
        self._materials = Materials()
        #
        self._coatings_material = 'none'
        self._coatings_thickness = 0.0
        self._coatings_density = 0.0
        #
        self._internal_fluid_name = 'water'
        self._internal_fluid_density = 1000.0
        #
        self._external_fluid_name = 'sea water'
        self._external_fluid_density = 1025.0
        #
        self._gravity = 9.81
        #
        self._length = 1.0

    def od(self, od):
        """Assign the outer diameter"""
        self._diameter_outer = od

    def t(self, t):
        """Assign the wall thickness"""
        self._wall_thickness = t

    def coatings(self, name, thickness_mm, density_kgm3):
        """Set key properties for the coatings on the pipe"""
        self._coatings_material = name
        self._coatings_thickness = thickness_mm
        self._coatings_density = density_kgm3

    def internal_fluid(self, name, density_kgm3):
        """Set the intenral fluids"""
        self._internal_fluid_name = name
        self._internal_fluid_density = density_kgm3

    def external_fluid(self, name, density_kgm3):
        """Set the intenral fluids"""
        self._external_fluid_name = name
        self._external_fluid_density = density_kgm3

    def material(self, material_name):
        """Set the material from the database"""
        self._materials.get_material(material_name)

    def length(self, length=None):
        """Set or return the length"""
        if length != None:
            self._length = length
        else:
            return self._length

    # -------------------------------------------------------------------------
    # Determine the properties
    # -------------------------------------------------------------------------
    def geometric_properties(self):
        """Calculate the goemetric properties of the pipe from wall thickness
        and outer diameter
        """

    def radius_inner(self):
        return 0.5 * (self._diameter_outer - 2.0 * self._wall_thickness)

    def radius_outer(self):
        return 0.5 * self._diameter_outer

    def radius_external(self):
        return 0.5 * (self._diameter_outer + 2.0 * self._coatings_thickness)

    def wall_thickness(self):
        return self._wall_thickness

    # -----------------
    def diameter_inner(self):
        return self._diameter_outer - 2.0 * self._wall_thickness

    def diameter_outer(self):
        return self._diameter_outer

    def diameter_external(self):
        return self._diameter_outer + 2.0 * self._coatings_thickness

    # -----------------
    def area_inner(self):
        return 0.25 * np.pi * self.diameter_inner()**2.0

    def area_steel(self):
        return self.area_outer() - self.area_inner()

    def area_outer(self):
        return 0.25 * np.pi * self.diameter_outer()**2.0

    def area_coatings(self):
        return self.area_external() - self.area_outer()

    def area_external(self):
        return 0.25 * np.pi * self.diameter_external()**2.0

    # -----------------
    def second_moment(self):
        return 0.015625 * np.pi * (self.diameter_outer()**4.0 - self.diameter_inner()**4.0)

    def radius_of_gyration(self):
        return np.sqrt(self.second_moment() / self.area_steel())

    # -----------------
    def mass_fluids(self):
        return self.area_inner() * self._internal_fluid_density

    def mass_steel(self):
        """Calculate the mass per unit length of the pipe"""
        return self.area_steel() * self._materials.density()

    def mass_coatings(self):
        return self.area_coatings() * self._coatings_density

    def mass_total(self):
        return self.mass_fluids() + self.mass_steel() + self.mass_coatings()

    def mass_buoyant(self):
        return self.mass_total() - self.area_external * self._external_fluid_density

    # -----------------
    def tension_limit(self, safety_factor=1.0):
        return safety_factor * self.area_steel() * self._materials.yield_stress()

    def bending_limit(self, safety_factor=1.0):
        return safety_factor * self.second_moment() * self._materials.yield_stress() / self.radius_outer()

    def pressure_internal_limit(self, safety_factor=1.0):
        return safety_factor * 2.0 * self._wall_thickness * self._materials.yield_stress() / self._diameter_outer

    # -----------------
    def euler_load(self, end_conditions='fixed'):
        """Return the Eular buckling load for a given length"""
        if end_conditions == 'fix-fix':
            factor = 4.0
        elif end_conditions == 'pin-fix':
            factor = 2.045
        elif end_conditions == 'pin-pin':
            factor = 1.0
        elif end_conditions == 'free-fix':
            factor = 0.25
        else:
            factor = 1.0
        #
        return factor * np.pi**2.0 * self._materials.youngs() * self.second_moment() / self._length**2.0

    # -------------------------------------------------------------------------
    # Display for information
    # -------------------------------------------------------------------------
    def display(self, SI=False):
        """Print a copy of the pipe details to the screen for information"""
        print("Pipe Details")

        if SI:
            print("Outer Diameter {:6.4g} m and wall thickness {:6.4g} m".format(self._diameter_outer, self._wall_thickness))
        else:
            print("Outer Diameter {:6.4g} mm and wall thickness {:6.4g} mm".format(1e3 * self._diameter_outer, 1e3 * self._wall_thickness))

        print("Material {}".format(self._materials.name()))
        #
        # Geometry Table
        print(" ")
        print("OD {:6.4g} mm, DI {:6.4g} mm, t {:6.4g} mm".format(
                1e3 * self.diameter_outer(),
                1e3 * self.diameter_inner(),
                1e3 * self.wall_thickness()
                ))
        print("Ai {:6.4g} m^2, As {:6.4g} m^2, Ae {:6.4g} m^2".format(
                self.area_inner(),
                self.area_steel(),
                self.area_outer()
                ))
        print("I {:6.4g} m^4".format(self.second_moment()))
        #
        #
        print(" ")
        if SI:
            print("Tension limit {:6g} N".format(self.tension_limit()))
            print("Bending limit {:6g} Nm".format(self.bending_limit()))
            print("Burst limit {:6g} Pa".format(self.pressure_internal_limit()))
        else:
            print("Tension limit {:6g} kN".format(1e-3 * self.tension_limit()))
            print("Bending limit {:6g} kNm".format(1e-3 * self.bending_limit()))
            print("Burst limit {:6g} MPa".format(1e-6 * self.pressure_internal_limit()))


text:
<?php

/** Zend_Locale */
require_once 'Zend/Locale.php';

/** Zend_Translate_Adapter */
require_once 'Zend/Translate/Adapter.php';

/**
 * @category   Zend
 * @package    Zend_Translate
 * @copyright  Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Translate_Adapter_Array extends Zend_Translate_Adapter
{
    private $_data = array();

    /**
     * Load translation data
     *
     * @param  string|array  $data
     * @param  string        $locale  Locale/Language to add data for, identical with locale identifier,
     *                                see Zend_Locale for more information
     * @param  array         $options OPTIONAL Options to use
     * @return array
     */
    protected function _loadTranslationData($data, $locale, array $options = array())
    {
        $this->_data = array();
        if (!is_array($data)) {
            if (file_exists($data)) {
                ob_start();
                $data = include($data);
                ob_end_clean();
            }
        }
        if (!is_array($data)) {
            require_once 'Zend/Translate/Exception.php';
            throw new Zend_Translate_Exception("Error including array or file '".$data."'");
        }

        if (!isset($this->_data[$locale])) {
            $this->_data[$locale] = array();
        }

        $this->_data[$locale] = $data + $this->_data[$locale];
        return $this->_data;
    }

    /**
     * returns the adapters name
     *
     * @return string
     */
    public function toString()
    {
        return "Array";
    }
}


text:
using GalaSoft.MvvmLight.Threading;
using Microsoft.Practices.ServiceLocation;
using Solocast.Core.Contracts;
using Solocast.Core.Interfaces;
using Solocast.Services;
using Solocast.UWP.ViewModels;
using System;
using System.Linq;
using System.Reflection;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.ApplicationModel.Core;
using Windows.Foundation.Metadata;
using Windows.Phone.UI.Input;
using Windows.UI;
using Windows.UI.Core;
using Windows.UI.ViewManagement;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Navigation;

namespace Solocast.UWP
{
    /// <summary>
    /// Provides application-specific behavior to supplement the default Application class.
    /// </summary>
    sealed partial class App : Application
    {
        /// <summary>
        /// Initializes the singleton application object.  This is the first line of authored code
        /// executed, and as such is the logical equivalent of main() or WinMain().
        /// </summary>
        public App()
        {
            this.InitializeComponent();
            this.Suspending += OnSuspending;
        }

        /// <summary>
        /// Invoked when the application is launched normally by the end user.  Other entry points
        /// will be used such as when the application is launched to open a specific file.
        /// </summary>
        /// <param name="e">Details about the launch request and process.</param>
        protected override async void OnLaunched(LaunchActivatedEventArgs e)
        {
#if DEBUG
            if (System.Diagnostics.Debugger.IsAttached)
            {
                //this.DebugSettings.EnableFrameRateCounter = true;
            }
#endif

            AppShell shell = Window.Current.Content as AppShell;

            // Do not repeat app initialization when the Window already has content,
            // just ensure that the window is active
            if (shell == null)
            {
                // Create a AppShell to act as the navigation context and navigate to the first page
                shell = new AppShell();

                // Set the default language
                shell.Language = Windows.Globalization.ApplicationLanguages.Languages[0];

                shell.AppFrame.NavigationFailed += OnNavigationFailed;

                if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
                {
                    //TODO: Load state from previously suspended application
                }
            }

            // Place our app shell in the current Window
            Window.Current.Content = shell;

            if (shell.AppFrame.Content == null)
            {
                // When the navigation stack isn't restored, navigate to the first page
                // suppressing the initial entrance animation.
                shell.AppFrame.Navigate(typeof(Views.PodcastsPage), e.Arguments);
            }

            // Ensure the current window is active
            Window.Current.Activate();
            DispatcherHelper.Initialize();
            var t = CoreApplication.GetCurrentView();
            t.TitleBar.ExtendViewIntoTitleBar = false;
            try
            {
                var s = StatusBar.GetForCurrentView();
                await s.HideAsync();
            }
            catch
            {
                //meh no status bar
            }
        }

        /// <summary>
        /// Invoked when Navigation to a certain page fails
        /// </summary>
        /// <param name="sender">The Frame which failed navigation</param>
        /// <param name="e">Details about the navigation failure</param>
        void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
        {
            throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
        }

        /// <summary>
        /// Invoked when application execution is being suspended.  Application state is saved
        /// without knowing whether the application will be terminated or resumed with the contents
        /// of memory still intact.
        /// </summary>
        /// <param name="sender">The source of the suspend request.</param>
        /// <param name="e">Details about the suspend request.</param>
        private async void OnSuspending(object sender, SuspendingEventArgs e)
        {
            var deferral = e.SuspendingOperation.GetDeferral();
            //TODO: Save application state and stop any background activity
            var podcastsVm = ServiceLocator.Current.GetInstance<PodcastsViewModel>();
            var podcastsService = ServiceLocator.Current.GetInstance<IPodcastStore<Podcast>>();

            await podcastsService.SaveAsync(podcastsVm.Podcasts.Select(p => p.Podcast));

            deferral.Complete();
        }
    }
}


text:
<?php
namespace CloudageTech\Mvc;
class ControllerContext{
    protected   $controller;
    protected   $routeData;
    function __construct($controller, $routeData){
        $this->controller = $controller;
        $this->routeData  = $routeData;
    }
    function GetController(){
        return $this->controller;
    }
    function GetRouteData(){
        return $this->routeData;
    }
    function GetControllerName(){
        return $this->routeData->GetValues()[':controller'];
    }
}


text:
package edu.pdx.cs410J.grader;

public class StudentFileMailerIT {
}