text:
concourse.Build = function ($el) {
  this.$el = $el;
  this.$abortBtn = this.$el.find('.js-abortBuild');
  this.buildID = this.$el.data('build-id');
  this.abortEndpoint = '/api/v1/builds/' + this.buildID + '/abort';
};

concourse.Build.prototype.bindEvents = function () {
  var _this = this;
  this.$abortBtn.on('click', function(event) {
    _this.abort();
  });
};

concourse.Build.prototype.abort = function() {
  var _this = this;

  $.ajax({
    method: 'POST',
    url: _this.abortEndpoint
  }).done(function (resp, jqxhr) {
    _this.$abortBtn.remove();
  }).error(function (resp) {
    _this.$abortBtn.addClass('errored');

    if (resp.status == 401) {
      concourse.redirect("/login");
    }
  });
};

$(function () {
  if ($('.js-build').length) {
    var build = new concourse.Build($('.js-build'));
    build.bindEvents();
  }
});


text:
/**
 * Returns.cpp -
 * @author: Jonathan Beard
 * @version: Sat Dec 28 13:15:48 2013
 */
#include "Returns.hpp"

using namespace Node;

Returns::Returns() : NodeAbstract( "Returns" )
{
   class_tree.addRelation( typeid( Node::NodeAbstract ).hash_code(),
                           typeid( Node::Returns ).hash_code() );
   /** nothing to do here **/
}

Returns::Returns( const std::string name ) : NodeAbstract( name )
{
   class_tree.addRelation( typeid( Node::NodeAbstract ).hash_code(),
                           typeid( Node::Returns ).hash_code() );
   /** nothing to do here **/
}

redpajama_set_name: RedPajamaGithub


text:
package com.netflix.kayenta.datadog.security;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.netflix.kayenta.datadog.service.DatadogRemoteService;
import com.netflix.kayenta.retrofit.config.RemoteService;
import com.netflix.kayenta.security.AccountCredentials;
import java.util.List;
import javax.validation.constraints.NotNull;
import lombok.Builder;
import lombok.Data;
import lombok.Singular;

@Builder
@Data
public class DatadogNamedAccountCredentials implements AccountCredentials<DatadogCredentials> {
  @NotNull private String name;

  @NotNull @Singular private List<Type> supportedTypes;

  @NotNull private DatadogCredentials credentials;

  @NotNull private RemoteService endpoint;

  @Override
  public String getType() {
    return "datadog";
  }

  @JsonIgnore DatadogRemoteService datadogRemoteService;
}


text:
from pyasn1.type import char
from pyasn1.type import constraint
from pyasn1.type import namedtype
from pyasn1.type import namedval
from pyasn1.type import tag
from pyasn1.type import univ

from pyasn1_modules import rfc5280

MAX = float('inf')

Certificate = rfc5280.Certificate

Name = rfc5280.Name

Extensions = rfc5280.Extensions

SubjectPublicKeyInfo = rfc5280.SubjectPublicKeyInfo

TBSCertificate = rfc5280.TBSCertificate

CertificatePolicies = rfc5280.CertificatePolicies

KeyIdentifier = rfc5280.KeyIdentifier

NameConstraints = rfc5280.NameConstraints

class CertPolicyFlags(univ.BitString):
    pass

CertPolicyFlags.namedValues = namedval.NamedValues(
    ('inhibitPolicyMapping', 0),
    ('requireExplicitPolicy', 1),
    ('inhibitAnyPolicy', 2)
)

class CertPathControls(univ.Sequence):
    pass

CertPathControls.componentType = namedtype.NamedTypes(
    namedtype.NamedType('taName', Name()),
    namedtype.OptionalNamedType('certificate', Certificate().subtype(
        implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0))),
    namedtype.OptionalNamedType('policySet', CertificatePolicies().subtype(
        implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 1))),
    namedtype.OptionalNamedType('policyFlags', CertPolicyFlags().subtype(
        implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 2))),
    namedtype.OptionalNamedType('nameConstr', NameConstraints().subtype(
        implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 3))),
    namedtype.OptionalNamedType('pathLenConstraint', univ.Integer().subtype(
        subtypeSpec=constraint.ValueRangeConstraint(0, MAX)).subtype(
        implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 4)))
)

class TrustAnchorTitle(char.UTF8String):
    pass

TrustAnchorTitle.subtypeSpec = constraint.ValueSizeConstraint(1, 64)

class TrustAnchorInfoVersion(univ.Integer):
    pass

TrustAnchorInfoVersion.namedValues = namedval.NamedValues(
    ('v1', 1)
)

class TrustAnchorInfo(univ.Sequence):
    pass

TrustAnchorInfo.componentType = namedtype.NamedTypes(
    namedtype.DefaultedNamedType('version', TrustAnchorInfoVersion().subtype(value='v1')),
    namedtype.NamedType('pubKey', SubjectPublicKeyInfo()),
    namedtype.NamedType('keyId', KeyIdentifier()),
    namedtype.OptionalNamedType('taTitle', TrustAnchorTitle()),
    namedtype.OptionalNamedType('certPath', CertPathControls()),
    namedtype.OptionalNamedType('exts', Extensions().subtype(explicitTag=tag.Tag(
        tag.tagClassContext, tag.tagFormatSimple, 1))),
    namedtype.OptionalNamedType('taTitleLangTag', char.UTF8String().subtype(
        implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 2)))
)

class TrustAnchorChoice(univ.Choice):
    pass

TrustAnchorChoice.componentType = namedtype.NamedTypes(
    namedtype.NamedType('certificate', Certificate()),
    namedtype.NamedType('tbsCert', TBSCertificate().subtype(
        explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 1))),
    namedtype.NamedType('taInfo', TrustAnchorInfo().subtype(
        explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 2)))
)

id_ct_trustAnchorList = univ.ObjectIdentifier('1.2.840.113549.1.9.16.1.34')

class TrustAnchorList(univ.SequenceOf):
    pass

TrustAnchorList.componentType = TrustAnchorChoice()
TrustAnchorList.subtypeSpec=constraint.ValueSizeConstraint(1, MAX)


text:
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use middle::freevars::freevar_entry;
use middle::freevars;
use middle::ty;
use middle::typeck;
use util::ppaux::{Repr, ty_to_str};
use util::ppaux::UserString;

use syntax::ast::*;
use syntax::attr;
use syntax::codemap::Span;
use syntax::owned_slice::OwnedSlice;
use syntax::print::pprust::{expr_to_str,path_to_str};
use syntax::{visit,ast_util};
use syntax::visit::Visitor;

// Kind analysis pass.
//
// There are several kinds defined by various operations. The most restrictive
// kind is noncopyable. The noncopyable kind can be extended with any number
// of the following attributes.
//
//  Send: Things that can be sent on channels or included in spawned closures. It
//  includes scalar types as well as classes and unique types containing only
//  sendable types.
//  'static: Things that do not contain references.
//
// This pass ensures that type parameters are only instantiated with types
// whose kinds are equal or less general than the way the type parameter was
// annotated (with the `Send` bound).
//
// It also verifies that noncopyable kinds are not copied. Sendability is not
// applied, since none of our language primitives send. Instead, the sending
// primitives in the stdlib are explicitly annotated to only take sendable
// types.

#[deriving(Clone)]
pub struct Context<'a> {
    tcx: &'a ty::ctxt,
}

impl<'a> Visitor<()> for Context<'a> {

    fn visit_expr(&mut self, ex: &Expr, _: ()) {
        check_expr(self, ex);
    }

    fn visit_fn(&mut self, fk: &visit::FnKind, fd: &FnDecl,
                b: &Block, s: Span, n: NodeId, _: ()) {
        check_fn(self, fk, fd, b, s, n);
    }

    fn visit_ty(&mut self, t: &Ty, _: ()) {
        check_ty(self, t);
    }

    fn visit_item(&mut self, i: &Item, _: ()) {
        check_item(self, i);
    }

    fn visit_pat(&mut self, p: &Pat, _: ()) {
        check_pat(self, p);
    }
}

pub fn check_crate(tcx: &ty::ctxt,
                   krate: &Crate) {
    let mut ctx = Context {
        tcx: tcx,
    };
    visit::walk_crate(&mut ctx, krate, ());
    tcx.sess.abort_if_errors();
}

fn check_struct_safe_for_destructor(cx: &mut Context,
                                    span: Span,
                                    struct_did: DefId) {
    let struct_tpt = ty::lookup_item_type(cx.tcx, struct_did);
    if !struct_tpt.generics.has_type_params() {
        let struct_ty = ty::mk_struct(cx.tcx, struct_did, ty::substs {
            regions: ty::NonerasedRegions(OwnedSlice::empty()),
            self_ty: None,
            tps: Vec::new()
        });
        if !ty::type_is_sendable(cx.tcx, struct_ty) {
            cx.tcx.sess.span_err(span,
                                 "cannot implement a destructor on a \
                                  structure that does not satisfy Send");
            cx.tcx.sess.span_note(span,
                                  "use \"#[unsafe_destructor]\" on the \
                                   implementation to force the compiler to \
                                   allow this");
        }
    } else {
        cx.tcx.sess.span_err(span,
                             "cannot implement a destructor on a structure \
                              with type parameters");
        cx.tcx.sess.span_note(span,
                              "use \"#[unsafe_destructor]\" on the \
                               implementation to force the compiler to \
                               allow this");
    }
}

fn check_impl_of_trait(cx: &mut Context, it: &Item, trait_ref: &TraitRef, self_type: &Ty) {
    let ast_trait_def = *cx.tcx.def_map.borrow()
                              .find(&trait_ref.ref_id)
                              .expect("trait ref not in def map!");
    let trait_def_id = ast_util::def_id_of_def(ast_trait_def);
    let trait_def = cx.tcx.trait_defs.borrow()
                          .find_copy(&trait_def_id)
                          .expect("trait def not in trait-defs map!");

    // If this trait has builtin-kind supertraits, meet them.
    let self_ty: ty::t = ty::node_id_to_type(cx.tcx, it.id);
    debug!("checking impl with self type {:?}", ty::get(self_ty).sty);
    check_builtin_bounds(cx, self_ty, trait_def.bounds, |missing| {
        cx.tcx.sess.span_err(self_type.span,
            format!("the type `{}', which does not fulfill `{}`, cannot implement this \
                  trait", ty_to_str(cx.tcx, self_ty), missing.user_string(cx.tcx)));
        cx.tcx.sess.span_note(self_type.span,
            format!("types implementing this trait must fulfill `{}`",
                 trait_def.bounds.user_string(cx.tcx)));
    });

    // If this is a destructor, check kinds.
    if cx.tcx.lang_items.drop_trait() == Some(trait_def_id) {
        match self_type.node {
            TyPath(_, ref bounds, path_node_id) => {
                assert!(bounds.is_none());
                let struct_def = cx.tcx.def_map.borrow().get_copy(&path_node_id);
                let struct_did = ast_util::def_id_of_def(struct_def);
                check_struct_safe_for_destructor(cx, self_type.span, struct_did);
            }
            _ => {
                cx.tcx.sess.span_bug(self_type.span,
                    "the self type for the Drop trait impl is not a path");
            }
        }
    }
}

fn check_item(cx: &mut Context, item: &Item) {
    if !attr::contains_name(item.attrs.as_slice(), "unsafe_destructor") {
        match item.node {
            ItemImpl(_, Some(ref trait_ref), self_type, _) => {
                check_impl_of_trait(cx, item, trait_ref, self_type);
            }
            _ => {}
        }
    }

    visit::walk_item(cx, item, ());
}

// Yields the appropriate function to check the kind of closed over
// variables. `id` is the NodeId for some expression that creates the
// closure.
fn with_appropriate_checker(cx: &Context,
                            id: NodeId,
                            b: |checker: |&Context, &freevar_entry||) {
    fn check_for_uniq(cx: &Context, fv: &freevar_entry, bounds: ty::BuiltinBounds) {
        // all captured data must be owned, regardless of whether it is
        // moved in or copied in.
        let id = ast_util::def_id_of_def(fv.def).node;
        let var_t = ty::node_id_to_type(cx.tcx, id);

        check_freevar_bounds(cx, fv.span, var_t, bounds, None);
    }

    fn check_for_block(cx: &Context, fv: &freevar_entry,
                       bounds: ty::BuiltinBounds, region: ty::Region) {
        let id = ast_util::def_id_of_def(fv.def).node;
        let var_t = ty::node_id_to_type(cx.tcx, id);
        // FIXME(#3569): Figure out whether the implicit borrow is actually
        // mutable. Currently we assume all upvars are referenced mutably.
        let implicit_borrowed_type = ty::mk_mut_rptr(cx.tcx, region, var_t);
        check_freevar_bounds(cx, fv.span, implicit_borrowed_type,
                             bounds, Some(var_t));
    }

    fn check_for_bare(cx: &Context, fv: &freevar_entry) {
        cx.tcx.sess.span_err(
            fv.span,
            "can't capture dynamic environment in a fn item; \
            use the || { ... } closure form instead");
    } // same check is done in resolve.rs, but shouldn't be done

    let fty = ty::node_id_to_type(cx.tcx, id);
    match ty::get(fty).sty {
        ty::ty_closure(box ty::ClosureTy {
            store: ty::UniqTraitStore, bounds, ..
        }) => b(|cx, fv| check_for_uniq(cx, fv, bounds)),

        ty::ty_closure(box ty::ClosureTy {
            store: ty::RegionTraitStore(region, _), bounds, ..
        }) => b(|cx, fv| check_for_block(cx, fv, bounds, region)),

        ty::ty_bare_fn(_) => {
            b(check_for_bare)
        }
        ref s => {
            cx.tcx.sess.bug(
                format!("expect fn type in kind checker, not {:?}", s));
        }
    }
}

// Check that the free variables used in a shared/sendable closure conform
// to the copy/move kind bounds. Then recursively check the function body.
fn check_fn(
    cx: &mut Context,
    fk: &visit::FnKind,
    decl: &FnDecl,
    body: &Block,
    sp: Span,
    fn_id: NodeId) {

    // Check kinds on free variables:
    with_appropriate_checker(cx, fn_id, |chk| {
        freevars::with_freevars(cx.tcx, fn_id, |freevars| {
            for fv in freevars.iter() {
                chk(cx, fv);
            }
        });
    });

    visit::walk_fn(cx, fk, decl, body, sp, ());
}

pub fn check_expr(cx: &mut Context, e: &Expr) {
    debug!("kind::check_expr({})", expr_to_str(e));

    // Handle any kind bounds on type parameters
    {
        let method_map = cx.tcx.method_map.borrow();
        let method = method_map.find(&typeck::MethodCall::expr(e.id));
        let item_substs = cx.tcx.item_substs.borrow();
        let r = match method {
            Some(method) => Some(&method.substs.tps),
            None => item_substs.find(&e.id).map(|s| &s.substs.tps)
        };
        for ts in r.iter() {
            let def_map = cx.tcx.def_map.borrow();
            let type_param_defs = match e.node {
              ExprPath(_) => {
                let did = ast_util::def_id_of_def(def_map.get_copy(&e.id));
                ty::lookup_item_type(cx.tcx, did).generics.type_param_defs.clone()
              }
              _ => {
                // Type substitutions should only occur on paths and
                // method calls, so this needs to be a method call.

                // Even though the callee_id may have been the id with
                // node_type_substs, e.id is correct here.
                match method {
                    Some(method) => {
                        ty::method_call_type_param_defs(cx.tcx, method.origin)
                    }
                    None => {
                        cx.tcx.sess.span_bug(e.span,
                            "non path/method call expr has type substs??");
                    }
                }
              }
            };
            if ts.len() != type_param_defs.len() {
                // Fail earlier to make debugging easier
                fail!("internal error: in kind::check_expr, length \
                      mismatch between actual and declared bounds: actual = \
                      {}, declared = {}",
                      ts.repr(cx.tcx),
                      type_param_defs.repr(cx.tcx));
            }
            for (&ty, type_param_def) in ts.iter().zip(type_param_defs.iter()) {
                check_typaram_bounds(cx, e.span, ty, type_param_def)
            }
        }
    }

    match e.node {
        ExprUnary(UnBox, interior) => {
            let interior_type = ty::expr_ty(cx.tcx, interior);
            let _ = check_static(cx.tcx, interior_type, interior.span);
        }
        ExprCast(source, _) => {
            let source_ty = ty::expr_ty(cx.tcx, source);
            let target_ty = ty::expr_ty(cx.tcx, e);
            check_trait_cast(cx, source_ty, target_ty, source.span);
        }
        ExprRepeat(element, count_expr) => {
            let count = ty::eval_repeat_count(cx.tcx, count_expr);
            if count > 1 {
                let element_ty = ty::expr_ty(cx.tcx, element);
                check_copy(cx, element_ty, element.span,
                           "repeated element will be copied");
            }
        }
        _ => {}
    }

    // Search for auto-adjustments to find trait coercions.
    match cx.tcx.adjustments.borrow().find(&e.id) {
        Some(adjustment) => {
            match *adjustment {
                ty::AutoObject(..) => {
                    let source_ty = ty::expr_ty(cx.tcx, e);
                    let target_ty = ty::expr_ty_adjusted(cx.tcx, e);
                    check_trait_cast(cx, source_ty, target_ty, e.span);
                }
                ty::AutoAddEnv(..) |
                ty::AutoDerefRef(..) => {}
            }
        }
        None => {}
    }

    visit::walk_expr(cx, e, ());
}

fn check_trait_cast(cx: &mut Context, source_ty: ty::t, target_ty: ty::t, span: Span) {
    check_cast_for_escaping_regions(cx, source_ty, target_ty, span);
    match ty::get(target_ty).sty {
        ty::ty_trait(box ty::TyTrait { bounds, .. }) => {
            check_trait_cast_bounds(cx, span, source_ty, bounds);
        }
        _ => {}
    }
}

fn check_ty(cx: &mut Context, aty: &Ty) {
    match aty.node {
        TyPath(_, _, id) => {
            match cx.tcx.item_substs.borrow().find(&id) {
                None => { }
                Some(ref item_substs) => {
                    let def_map = cx.tcx.def_map.borrow();
                    let did = ast_util::def_id_of_def(def_map.get_copy(&id));
                    let generics = ty::lookup_item_type(cx.tcx, did).generics;
                    let type_param_defs = generics.type_param_defs();
                    for (&ty, type_param_def) in
                        item_substs.substs.tps.iter().zip(
                            type_param_defs.iter())
                    {
                        check_typaram_bounds(cx, aty.span, ty, type_param_def)
                    }
                }
            }
        }
        _ => {}
    }
    visit::walk_ty(cx, aty, ());
}

// Calls "any_missing" if any bounds were missing.
pub fn check_builtin_bounds(cx: &Context,
                            ty: ty::t,
                            bounds: ty::BuiltinBounds,
                            any_missing: |ty::BuiltinBounds|) {
    let kind = ty::type_contents(cx.tcx, ty);
    let mut missing = ty::EmptyBuiltinBounds();
    for bound in bounds.iter() {
        if !kind.meets_bound(cx.tcx, bound) {
            missing.add(bound);
        }
    }
    if !missing.is_empty() {
        any_missing(missing);
    }
}

pub fn check_typaram_bounds(cx: &Context,
                            sp: Span,
                            ty: ty::t,
                            type_param_def: &ty::TypeParameterDef) {
    check_builtin_bounds(cx,
                         ty,
                         type_param_def.bounds.builtin_bounds,
                         |missing| {
        cx.tcx.sess.span_err(
            sp,
            format!("instantiating a type parameter with an incompatible type \
                  `{}`, which does not fulfill `{}`",
                 ty_to_str(cx.tcx, ty),
                 missing.user_string(cx.tcx)));
    });
}

pub fn check_freevar_bounds(cx: &Context, sp: Span, ty: ty::t,
                            bounds: ty::BuiltinBounds, referenced_ty: Option<ty::t>)
{
    check_builtin_bounds(cx, ty, bounds, |missing| {
        // Will be Some if the freevar is implicitly borrowed (stack closure).
        // Emit a less mysterious error message in this case.
        match referenced_ty {
            Some(rty) => cx.tcx.sess.span_err(sp,
                format!("cannot implicitly borrow variable of type `{}` in a bounded \
                      stack closure (implicit reference does not fulfill `{}`)",
                     ty_to_str(cx.tcx, rty), missing.user_string(cx.tcx))),
            None => cx.tcx.sess.span_err(sp,
                format!("cannot capture variable of type `{}`, which does \
                      not fulfill `{}`, in a bounded closure",
                     ty_to_str(cx.tcx, ty), missing.user_string(cx.tcx))),
        }
        cx.tcx.sess.span_note(
            sp,
            format!("this closure's environment must satisfy `{}`",
                 bounds.user_string(cx.tcx)));
    });
}

pub fn check_trait_cast_bounds(cx: &Context, sp: Span, ty: ty::t,
                               bounds: ty::BuiltinBounds) {
    check_builtin_bounds(cx, ty, bounds, |missing| {
        cx.tcx.sess.span_err(sp,
            format!("cannot pack type `{}`, which does not fulfill \
                  `{}`, as a trait bounded by {}",
                 ty_to_str(cx.tcx, ty), missing.user_string(cx.tcx),
                 bounds.user_string(cx.tcx)));
    });
}

fn check_copy(cx: &Context, ty: ty::t, sp: Span, reason: &str) {
    debug!("type_contents({})={}",
           ty_to_str(cx.tcx, ty),
           ty::type_contents(cx.tcx, ty).to_str());
    if ty::type_moves_by_default(cx.tcx, ty) {
        cx.tcx.sess.span_err(
            sp, format!("copying a value of non-copyable type `{}`",
                     ty_to_str(cx.tcx, ty)));
        cx.tcx.sess.span_note(sp, format!("{}", reason));
    }
}

pub fn check_static(tcx: &ty::ctxt, ty: ty::t, sp: Span) -> bool {
    if !ty::type_is_static(tcx, ty) {
        match ty::get(ty).sty {
          ty::ty_param(..) => {
            tcx.sess.span_err(sp,
                format!("value may contain references; \
                         add `'static` bound to `{}`", ty_to_str(tcx, ty)));
          }
          _ => {
            tcx.sess.span_err(sp, "value may contain references");
          }
        }
        false
    } else {
        true
    }
}

/// This is rather subtle.  When we are casting a value to an instantiated
/// trait like `a as trait<'r>`, regionck already ensures that any references
/// that appear in the type of `a` are bounded by `'r` (ed.: rem
/// FIXME(#5723)).  However, it is possible that there are *type parameters*
/// in the type of `a`, and those *type parameters* may have references
/// within them.  We have to guarantee that the regions which appear in those
/// type parameters are not obscured.
///
/// Therefore, we ensure that one of three conditions holds:
///
/// (1) The trait instance cannot escape the current fn.  This is
/// guaranteed if the region bound `&r` is some scope within the fn
/// itself.  This case is safe because whatever references are
/// found within the type parameter, they must enclose the fn body
/// itself.
///
/// (2) The type parameter appears in the type of the trait.  For
/// example, if the type parameter is `T` and the trait type is
/// `deque<T>`, then whatever references may appear in `T` also
/// appear in `deque<T>`.
///
/// (3) The type parameter is sendable (and therefore does not contain
/// references).
///
/// FIXME(#5723)---This code should probably move into regionck.
pub fn check_cast_for_escaping_regions(
    cx: &Context,
    source_ty: ty::t,
    target_ty: ty::t,
    source_span: Span)
{
    // Determine what type we are casting to; if it is not a trait, then no
    // worries.
    match ty::get(target_ty).sty {
        ty::ty_trait(..) => {}
        _ => { return; }
    }

    // Collect up the regions that appear in the target type.  We want to
    // ensure that these lifetimes are shorter than all lifetimes that are in
    // the source type.  See test `src/test/compile-fail/regions-trait-2.rs`
    let mut target_regions = Vec::new();
    ty::walk_regions_and_ty(
        cx.tcx,
        target_ty,
        |r| {
            if !r.is_bound() {
                target_regions.push(r);
            }
        },
        |_| ());

    // Check, based on the region associated with the trait, whether it can
    // possibly escape the enclosing fn item (note that all type parameters
    // must have been declared on the enclosing fn item).
    if target_regions.iter().any(|r| is_ReScope(*r)) {
        return; /* case (1) */
    }

    // Assuming the trait instance can escape, then ensure that each parameter
    // either appears in the trait type or is sendable.
    let target_params = ty::param_tys_in_type(target_ty);
    ty::walk_regions_and_ty(
        cx.tcx,
        source_ty,

        |_r| {
            // FIXME(#5723) --- turn this check on once &Objects are usable
            //
            // if !target_regions.iter().any(|t_r| is_subregion_of(cx, *t_r, r)) {
            //     cx.tcx.sess.span_err(
            //         source_span,
            //         format!("source contains reference with lifetime \
            //               not found in the target type `{}`",
            //              ty_to_str(cx.tcx, target_ty)));
            //     note_and_explain_region(
            //         cx.tcx, "source data is only valid for ", r, "");
            // }
        },

        |ty| {
            match ty::get(ty).sty {
                ty::ty_param(source_param) => {
                    if target_params.iter().any(|x| x == &source_param) {
                        /* case (2) */
                    } else {
                        check_static(cx.tcx, ty, source_span); /* case (3) */
                    }
                }
                _ => {}
            }
        });

    fn is_ReScope(r: ty::Region) -> bool {
        match r {
            ty::ReScope(..) => true,
            _ => false
        }
    }
}

// Ensure that `ty` has a statically known size (i.e., it has the `Sized` bound).
fn check_sized(tcx: &ty::ctxt, ty: ty::t, name: StrBuf, sp: Span) {
    if !ty::type_is_sized(tcx, ty) {
        tcx.sess.span_err(sp, format!("variable `{}` has dynamically sized type `{}`",
                                      name, ty_to_str(tcx, ty)));
    }
}

// Check that any variables in a pattern have types with statically known size.
fn check_pat(cx: &mut Context, pat: &Pat) {
    let var_name = match pat.node {
        PatWild => Some("_".to_strbuf()),
        PatIdent(_, ref path, _) => Some(path_to_str(path).to_strbuf()),
        _ => None
    };

    match var_name {
        Some(name) => {
            let types = cx.tcx.node_types.borrow();
            let ty = types.find(&(pat.id as uint));
            match ty {
                Some(ty) => {
                    debug!("kind: checking sized-ness of variable {}: {}",
                           name, ty_to_str(cx.tcx, *ty));
                    check_sized(cx.tcx, *ty, name, pat.span);
                }
                None => {} // extern fn args
            }
        }
        None => {}
    }

    visit::walk_pat(cx, pat, ());
}


text:
package br.jus.jfms.jef;

public interface ITicketCollector {
	public void collect(String ticket, String callcenter);
}


text:
namespace com.xcitestudios.Generic.Text.Interfaces
{
    /// <summary>
    /// General interface for something that can render a template style string.
    /// </summary>
    public interface ITemplated
    {
        /// <summary>
        /// Template version of the content to be used during rendering.
        /// </summary>
        string Content { get; set; }

        /// <summary>
        /// Object passed in to replace items in the content.
        /// </summary>
        object Context { get; set; }

        /// <summary>
        /// Renders content given the context object.
        /// </summary>
        /// <returns>String content rendered using the values in <see cref="P:context"/></returns>
        string Render();
    }
}


text:
package org.sindice.siren.util;

import java.io.CharArrayReader;

/**
 * Implementation of the {@link CharArrayReader} that allows to reset the reader
 * to a new char array input.
 */
public class ReusableCharArrayReader extends CharArrayReader {

  /**
   * @param buf
   */
  public ReusableCharArrayReader(final char[] buf) {
    super(buf);
  }

  public ReusableCharArrayReader(final char[] buf, final int offset, final int length) {
    super(buf, offset, length);
  }

  public void reset(final char[] toReset) {
    this.buf = toReset;
    this.pos = 0;
    this.count = toReset.length;
  }

  public void reset(final char[] toReset, final int offset, final int len) {
    this.buf = toReset;
    this.pos = offset;
    this.count = len;
  }

  @Override
  public String toString() {
    return new String(buf, this.pos, this.count);
  }

}


text:
import chai from 'chai';
import sinonChai from 'sinon-chai';
import { cleanObject } from '../../src/lib/cleanObject';

const expect = chai.expect;

chai.use(sinonChai);

describe('lib: cleanObject', () => {
  it('is a function', () => {
    expect(cleanObject).to.be.a('function');
  });

  const obj = { foo: null, bar: undefined, baz: true };

  it('removes null and undefined values', () => {
    expect(cleanObject(obj)).to.eql({ baz: true });
  });
});


text:
print('Yay! Printing')
print("I'd much rather you 'not'")
print('I "said" do not touch this')


text:
function Set-DODropletKernel
{
<#
.Synopsis
   The Restore-DODropletSnapshot cmdlet restores a droplet to a specified backup image.
.DESCRIPTION
   The Restore-DODropletSnapshot cmdlet restores a droplet to a specified backup image.

   An API key is required to use this cmdlet.
.EXAMPLE
   Restore-DODropletSnapshot -APIKey b7d03a6947b217efb6f3ec3bd3504582

   id           : 3164444
   name         : example.com
   memory       : 512
   vcpus        : 1
   disk         : 20
   locked       : False
   status       : active
   kernel       : @{id=2233; name=Ubuntu 14.04 x64 vmlinuz-3.13.0-37-generic; version=3.13.0-37-generic}
   created_at   : 2014-11-14T16:29:21Z
   features     : {backups, ipv6, virtio}
   backup_ids   : {7938002}
   snapshot_ids : {}
   image        : @{id=6918990; name=14.04 x64; distribution=Ubuntu; slug=ubuntu-14-04-x64; public=True;
                  regions=System.Object[]; created_at=2014-10-17T20:24:33Z; type=snapshot; min_disk_size=20}
   size         :
   size_slug    : 512mb
   networks     : @{v4=System.Object[]; v6=System.Object[]}
   region       : @{name=New York 3; slug=nyc3; sizes=System.Object[]; features=System.Object[]; available=}

   The example above returns the information for all droplets available to the current API bearer.

.EXAMPLE
   PS C:\>Restore-DODropletSnapshot -APIKey b7d03a6947b217efb6f3ec3bd3504582 -DropletID 3164444, 3164445

   id           : 3164444
   name         : example.com
   memory       : 512
   vcpus        : 1
   disk         : 20
   locked       : False
   status       : active
   kernel       : @{id=2233; name=Ubuntu 14.04 x64 vmlinuz-3.13.0-37-generic; version=3.13.0-37-generic}
   created_at   : 2014-11-14T16:29:21Z
   features     : {backups, ipv6, virtio}
   backup_ids   : {7938002}
   snapshot_ids : {}
   image        : @{id=6918990; name=14.04 x64; distribution=Ubuntu; slug=ubuntu-14-04-x64; public=True;
                  regions=System.Object[]; created_at=2014-10-17T20:24:33Z; type=snapshot; min_disk_size=20}
   size         :
   size_slug    : 512mb
   networks     : @{v4=System.Object[]; v6=System.Object[]}
   region       : @{name=New York 3; slug=nyc3; sizes=System.Object[]; features=System.Object[]; available=}

   id           : 3164445
   name         : example.org
   memory       : 512
   vcpus        : 1
   disk         : 20
   locked       : False
   status       : active
   kernel       : @{id=2233; name=Ubuntu 14.04 x64 vmlinuz-3.13.0-37-generic; version=3.13.0-37-generic}
   created_at   : 2014-11-14T16:42:36Z
   features     : {backups, ipv6, virtio}
   backup_ids   : {7938003}
   snapshot_ids : {}
   image        : @{id=6918990; name=14.04 x64; distribution=Ubuntu; slug=ubuntu-14-04-x64; public=True;
                  regions=System.Object[]; created_at=2014-10-17T20:24:33Z; type=snapshot; min_disk_size=20}
   size         :
   size_slug    : 512mb
   networks     : @{v4=System.Object[]; v6=System.Object[]}
   region       : @{name=New York 3; slug=nyc3; sizes=System.Object[]; features=System.Object[]; available=}

   The example above returns the information for all the specified droplet IDs available to the current API bearer.

.INPUTS
   System.String

       This cmdlet requires the API key to be passed as a string.

   System.UInt64

       This cmdlet requires the droplet ID to be passed as a 64-bit, unsiged integer.
.OUTPUTS
   PS.DigitalOcean.Action

       A PS.DigitalOcean.Action object holding the action info is returned.
.ROLE
   PS.DigitalOcean
.FUNCTIONALITY
   PS.DigitalOcean
#>
    [CmdletBinding(SupportsShouldProcess=$true,
                   ConfirmImpact='High',
                   PositionalBinding=$true)]
    [Alias('sdovmk')]
    [OutputType('PS.DigitalOcean.Action')]
    Param
    (
        # Uniqe ID of the Droplet.
        [Parameter(Mandatory=$true,
                   Position=0)]
        [ValidateNotNull()]
        [ValidateNotNullOrEmpty()]
        [Alias('ID')]
        [UInt64[]]$DropletID,
        # Uniqe ID or slug of the backup image.
        [Parameter(Mandatory=$true,
                   Position=1)]
        [ValidateNotNull()]
        [ValidateNotNullOrEmpty()]
        [UInt64[]]$Kernel,
        # Used to bypass confirmation prompts.
        [Parameter(Mandatory=$false,
                   Position=2)]
        [ValidateNotNull()]
        [ValidateNotNullOrEmpty()]
        [Switch]$Force,
        # API key to access account.
        [Parameter(Mandatory=$false,
                   Position=3)]
        [ValidateNotNull()]
        [ValidateNotNullOrEmpty()]
        [Alias('Key','Token')]
        [String]$APIKey = $script:SavedDOAPIKey
    )

    Begin
    {
        if(-not $APIKey)
        {
            throw 'Use Connect-DOCloud to specifiy the API key.'
        }
        [String]$sessionBody = @{'type'='change_kernel';'kernel'=$Kernel} | ConvertTo-Json
        [Hashtable]$sessionHeaders = @{'Authorization'="Bearer $APIKey";'Content-Type'='application/json'}
        [Uri]$doApiUri = 'https://api.digitalocean.com/v2/droplets/'
    }
    Process
    {
        foreach($droplet in $DropletID)
        {
            if($Force -or $PSCmdlet.ShouldProcess("Changing DropletID $droplet to kernel $Kernel."))
            {
                try
                {
                    $doApiUriWithID = '{0}{1}' -f $doApiUri,"$droplet/actions"
                    $doInfo = Invoke-RestMethod -Method POST -Uri $doApiUriWithID -Headers $sessionHeaders -Body $sessionBody -ErrorAction Stop
                    $doReturnInfo = [PSCustomObject]@{
                        'ActionID' = $doInfo.action.id
                        'Status' = $doInfo.action.status
                        'Type' = $doInfo.action.type
                        'StartedAt' = $doInfo.action.started_at
                        'CompletedAt' = $doInfo.action.completed_at
                        'ResourceID' = $doInfo.action.resource_id
                        'ResourceType' = $doInfo.action.resource_type
                        'Region' = $doInfo.action.region_slug
                    }
                    # DoReturnInfo is returned after Add-ObjectDetail is processed.
                    Add-ObjectDetail -InputObject $doReturnInfo -TypeName 'PS.DigitalOcean.Action'
                }
                catch
                {
                    $errorDetail = $_.Exception.Message
                    Write-Warning "Could not change the kernel to $Kernel for droplet $droplet.`n`r$errorDetail"
                }
            }
        }
    }
}


text:
using Content.Shared.Damage;
using Robust.Shared.Serialization.TypeSerializers.Implementations.Custom.Prototype;
using Content.Shared.Damage.Prototypes;

namespace Content.Server.Destructible.Thresholds.Triggers
{
    /// <summary>
    ///     A trigger that will activate when the amount of damage received
    ///     of the specified type is above the specified threshold.
    /// </summary>
    [Serializable]
    [DataDefinition]
    public sealed class DamageTypeTrigger : IThresholdTrigger
    {
        [DataField("damageType", required:true, customTypeSerializer: typeof(PrototypeIdSerializer<DamageTypePrototype>))]
        public string DamageType { get; set; } = default!;

        [DataField("damage", required: true)]
        public int Damage { get; set; } = default!;

        public bool Reached(DamageableComponent damageable, DestructibleSystem system)
        {
            return damageable.Damage.DamageDict.TryGetValue(DamageType, out var damageReceived) &&
                   damageReceived >= Damage;
        }
    }
}


text:
#ifndef _REGION_ALLOCATOR_H_
#define _REGION_ALLOCATOR_H_

#include <stdio.h>

typedef struct region region_type;

#define DEFAULT_CHUNK_SIZE         4096
#define DEFAULT_LARGE_OBJECT_SIZE  (DEFAULT_CHUNK_SIZE / 8)
#define DEFAULT_INITIAL_CLEANUP_SIZE 16

/*
 * mmap allocator constants
 *
 */
#ifdef USE_MMAP_ALLOC

/* header starts with size_t containing allocated size info and has at least 16 bytes to align the returned memory */
#define MMAP_ALLOC_HEADER_SIZE (sizeof(size_t) >= 16 ? (sizeof(size_t)) : 16)

/* mmap allocator uses chunks of 32 4kB pages */
#define MMAP_ALLOC_CHUNK_SIZE		((32 * 4096) - MMAP_ALLOC_HEADER_SIZE)
#define MMAP_ALLOC_LARGE_OBJECT_SIZE	(MMAP_ALLOC_CHUNK_SIZE / 8)
#define MMAP_ALLOC_INITIAL_CLEANUP_SIZE	16

#endif /* USE_MMAP_ALLOC */

/*
 * Create a new region.
 */
region_type *region_create(void *(*allocator)(size_t),
			   void (*deallocator)(void *));

/*
 * Create a new region, with chunk size and large object size.
 * Note that large_object_size must be <= chunk_size.
 * Anything larger than the large object size is individually alloced.
 * large_object_size = chunk_size/8 is reasonable;
 * initial_cleanup_size is the number of preallocated ptrs for cleanups.
 * The cleanups are in a growing array, and it must start larger than zero.
 * If recycle is true, environmentally friendly memory recycling is be enabled.
 */
region_type *region_create_custom(void *(*allocator)(size_t),
				  void (*deallocator)(void *),
				  size_t chunk_size,
				  size_t large_object_size,
				  size_t initial_cleanup_size,
				  int recycle);

/*
 * Destroy REGION.  All memory associated with REGION is freed as if
 * region_free_all was called.
 */
void region_destroy(region_type *region);

/*
 * Add a cleanup to REGION.  ACTION will be called with DATA as
 * parameter when the region is freed or destroyed.
 *
 * Returns 0 on failure.
 */
size_t region_add_cleanup(region_type *region,
			  void (*action)(void *),
			  void *data);

/*
 * Remove cleanup, both action and data must match exactly.
 */
void region_remove_cleanup(region_type *region,
        void (*action)(void *), void *data);

/*
 * Allocate SIZE bytes of memory inside REGION.  The memory is
 * deallocated when region_free_all is called for this region.
 */
void *region_alloc(region_type *region, size_t size);

/** Allocate array with integer overflow checks, in region */
void *region_alloc_array(region_type *region, size_t num, size_t size);

/*
 * Allocate SIZE bytes of memory inside REGION and copy INIT into it.
 * The memory is deallocated when region_free_all is called for this
 * region.
 */
void *region_alloc_init(region_type *region, const void *init, size_t size);

/**
 * Allocate array (with integer overflow check on sizes), and init with
 * the given array copied into it.  Allocated in the region
 */
void *region_alloc_array_init(region_type *region, const void *init,
	size_t num, size_t size);

/*
 * Allocate SIZE bytes of memory inside REGION that are initialized to
 * 0.  The memory is deallocated when region_free_all is called for
 * this region.
 */
void *region_alloc_zero(region_type *region, size_t size);

/**
 * Allocate array (with integer overflow check on sizes), and zero it.
 * Allocated in the region.
 */
void *region_alloc_array_zero(region_type *region, size_t num, size_t size);

/*
 * Run the cleanup actions and free all memory associated with REGION.
 */
void region_free_all(region_type *region);

/*
 * Duplicate STRING and allocate the result in REGION.
 */
char *region_strdup(region_type *region, const char *string);

/*
 * Recycle an allocated memory block. Pass size used to alloc it.
 * Does nothing if recycling is not enabled for the region.
 */
void region_recycle(region_type *region, void *block, size_t size);

/*
 * Print some REGION statistics to OUT.
 */
void region_dump_stats(region_type *region, FILE *out);

/* get size of recyclebin */
size_t region_get_recycle_size(region_type* region);
/* get size of region memory in use */
size_t region_get_mem(region_type* region);
/* get size of region memory unused */
size_t region_get_mem_unused(region_type* region);

/* Debug print REGION statistics to LOG. */
void region_log_stats(region_type *region);

#endif /* _REGION_ALLOCATOR_H_ */


text:
#if UNITY_EDITOR || DEVELOPMENT_BUILD
#define DEVELOPMENT
#endif

using System;
using System.Collections;
using System.Collections.Generic;
using BeauRoutine.Internal;
using UnityEngine;

namespace BeauRoutine
{
    public partial struct Routine
    {
        #region Start

        /// <summary>
        /// Runs a routine.
        /// </summary>
        static public Routine Start(IEnumerator inCoroutine)
        {
            Manager m = Manager.Get();
            if (m != null)
                return m.RunFiber(null, inCoroutine);
            return Routine.Null;
        }

        /// <summary>
        /// Runs a routine.
        /// </summary>
        static public Routine Start(MonoBehaviour inHost, IEnumerator inCoroutine)
        {
            Manager m = Manager.Get();
            if (m != null)
                return m.RunFiber(inHost, inCoroutine);
            return Routine.Null;
        }

        #endregion

        #region Stop

        /// <summary>
        /// Stops all currently running routines.
        /// </summary>
        static public void StopAll()
        {
            Manager m = Manager.Get();
            if (m != null)
                m.Fibers.RunQueryAll(new NullQuery(), new StopOperation());
        }

        /// <summary>
        /// Stops currently running routines with the given name.
        /// </summary>
        static public void Stop(string inName)
        {
            Manager m = Manager.Get();
            if (m != null)
                m.Fibers.RunQueryAll(new NameQuery() { Name = inName }, new StopOperation());
        }

        /// <summary>
        /// Stops all currently running routines that match up with the given group mask.
        /// </summary>
        static public void Stop(int inGroupMask)
        {
            Manager m = Manager.Get();
            if (m != null)
                m.Fibers.RunQueryAll(new GroupQuery() { GroupMask = inGroupMask }, new StopOperation());
        }

        /// <summary>
        /// Stops all currently running routines on the given host.
        /// </summary>
        static public void StopAll(MonoBehaviour inHost)
        {
            Manager m = Manager.Get();
            if (m != null)
                m.Fibers.RunQueryAll(new MonoBehaviourQuery() { Host = inHost }, new StopOperation());
        }

        /// <summary>
        /// Stops currently running routines on the given host with the given name.
        /// </summary>
        static public void Stop(MonoBehaviour inHost, string inName)
        {
            Manager m = Manager.Get();
            if (m != null)
                m.Fibers.RunQueryAll(new MonoBehaviourNameQuery() { Host = inHost, Name = inName }, new StopOperation());
        }

        /// <summary>
        /// Stops currently running routines on the given host in the given groups.
        /// </summary>
        static public void Stop(MonoBehaviour inHost, int inGroupMask)
        {
            Manager m = Manager.Get();
            if (m != null)
                m.Fibers.RunQueryAll(new MonoBehaviourGroupQuery() { Host = inHost, GroupMask = inGroupMask }, new StopOperation());
        }

        /// <summary>
        /// Stops all currently running routines on the given host.
        /// </summary>
        static public void StopAll(GameObject inHost)
        {
            Manager m = Manager.Get();
            if (m != null)
                m.Fibers.RunQueryAll(new GameObjectQuery() { Host = inHost }, new StopOperation());
        }

        /// <summary>
        /// Stops currently running routines on the given host with the given name.
        /// </summary>
        static public void Stop(GameObject inHost, string inName)
        {
            Manager m = Manager.Get();
            if (m != null)
                m.Fibers.RunQueryAll(new GameObjectNameQuery() { Host = inHost, Name = inName }, new StopOperation());
        }

        /// <summary>
        /// Stops currently running routines on the given host in the given groups.
        /// </summary>
        static public void Stop(GameObject inHost, int inGroupMask)
        {
            Manager m = Manager.Get();
            if (m != null)
                m.Fibers.RunQueryAll(new GameObjectGroupQuery() { Host = inHost, GroupMask = inGroupMask }, new StopOperation());
        }

        #endregion

        #region Pause

        /// <summary>
        /// Pauses all currently running routines.
        /// </summary>
        static public void PauseAll()
        {
            Manager m = Manager.Get();
            if (m != null)
                m.Paused = true;
        }

        /// <summary>
        /// Pauses all currently running routines on the given host.
        /// </summary>
        static public void PauseAll(MonoBehaviour inHost)
        {
            Manager m = Manager.Get();
            if (m != null)
                m.Fibers.RunQueryAll(new MonoBehaviourQuery() { Host = inHost }, new PauseOperation());
        }

        /// <summary>
        /// Pauses currently running routines on the given host with the given name.
        /// </summary>
        static public void Pause(MonoBehaviour inHost, string inName)
        {
            Manager m = Manager.Get();
            if (m != null)
                m.Fibers.RunQueryAll(new MonoBehaviourNameQuery() { Host = inHost, Name = inName }, new PauseOperation());
        }

        /// <summary>
        /// Pauses all currently running routines on the given host.
        /// </summary>
        static public void PauseAll(GameObject inHost)
        {
            Manager m = Manager.Get();
            if (m != null)
                m.Fibers.RunQueryAll(new GameObjectQuery() { Host = inHost }, new PauseOperation());
        }

        /// <summary>
        /// Pauses currently running routines on the given host with the given name.
        /// </summary>
        static public void Pause(GameObject inHost, string inName)
        {
            Manager m = Manager.Get();
            if (m != null)
                m.Fibers.RunQueryAll(new GameObjectNameQuery() { Host = inHost, Name = inName }, new PauseOperation());
        }

        /// <summary>
        /// Pauses currently running routines with the given name.
        /// </summary>
        static public void Pause(string inName)
        {
            Manager m = Manager.Get();
            if (m != null)
                m.Fibers.RunQueryAll(new NameQuery() { Name = inName }, new PauseOperation());
        }

        #endregion

        #region Resume

        /// <summary>
        /// Resumes all currently running routines.
        /// </summary>
        static public void ResumeAll()
        {
            Manager m = Manager.Get();
            if (m != null)
                m.Paused = false;
        }

        /// <summary>
        /// Resumes all currently running routines on the given host.
        /// </summary>
        static public void ResumeAll(MonoBehaviour inHost)
        {
            Manager m = Manager.Get();
            if (m != null)
                m.Fibers.RunQueryAll(new MonoBehaviourQuery() { Host = inHost }, new ResumeOperation());
        }

        /// <summary>
        /// Resumes currently running routines on the given host with the given name.
        /// </summary>
        static public void Resume(MonoBehaviour inHost, string inName)
        {
            Manager m = Manager.Get();
            if (m != null)
                m.Fibers.RunQueryAll(new MonoBehaviourNameQuery() { Host = inHost, Name = inName }, new ResumeOperation());
        }

        /// <summary>
        /// Resumes all currently running routines on the given host.
        /// </summary>
        static public void ResumeAll(GameObject inHost)
        {
            Manager m = Manager.Get();
            if (m != null)
                m.Fibers.RunQueryAll(new GameObjectQuery() { Host = inHost }, new ResumeOperation());
        }

        /// <summary>
        /// Resumes currently running routines on the given host with the given name.
        /// </summary>
        static public void Resume(GameObject inHost, string inName)
        {
            Manager m = Manager.Get();
            if (m != null)
                m.Fibers.RunQueryAll(new GameObjectNameQuery() { Host = inHost, Name = inName }, new ResumeOperation());
        }

        /// <summary>
        /// Resumes currently running routines with the given name.
        /// </summary>
        static public void Resume(string inName)
        {
            Manager m = Manager.Get();
            if (m != null)
                m.Fibers.RunQueryAll(new NameQuery() { Name = inName }, new ResumeOperation());
        }

        #endregion

        #region Query

        /// <summary>
        /// Adds all currently running routines on the given host to the given collection.
        /// </summary>
        static public void FindAll(MonoBehaviour inHost, ref ICollection<Routine> ioRoutines)
        {
            Manager m = Manager.Get();
            if (m != null)
                m.Fibers.RunQueryAll(new MonoBehaviourQuery() { Host = inHost }, new NullOperation(), ref ioRoutines);
        }

        /// <summary>
        /// Adds currently running routines on the given host with the given name to the given collection.
        /// </summary>
        static public void Find(MonoBehaviour inHost, string inName, ref ICollection<Routine> ioRoutines)
        {
            Manager m = Manager.Get();
            if (m != null)
                m.Fibers.RunQueryAll(new MonoBehaviourNameQuery() { Host = inHost, Name = inName }, new NullOperation(), ref ioRoutines);
        }

        /// <summary>
        /// Returns the first currently running routine on the given host with the given name.
        /// </summary>
        static public Routine Find(MonoBehaviour inHost, string inName)
        {
            Manager m = Manager.Get();
            if (m != null)
                return m.Fibers.RunQueryFirst(new MonoBehaviourNameQuery() { Host = inHost, Name = inName }, new NullOperation());
            return Routine.Null;
        }

        /// <summary>
        /// Adds all currently running routines on the given host to the given collection.
        /// </summary>
        static public void FindAll(GameObject inHost, ref ICollection<Routine> ioRoutines)
        {
            Manager m = Manager.Get();
            if (m != null)
                m.Fibers.RunQueryAll(new GameObjectQuery() { Host = inHost }, new NullOperation(), ref ioRoutines);
        }

        /// <summary>
        /// Adds currently running routines on the given host with the given name to the given collection.
        /// </summary>
        static public void Find(GameObject inHost, string inName, ref ICollection<Routine> ioRoutines)
        {
            Manager m = Manager.Get();
            if (m != null)
                m.Fibers.RunQueryAll(new GameObjectNameQuery() { Host = inHost, Name = inName }, new NullOperation(), ref ioRoutines);
        }

        /// <summary>
        /// Returns the first currently running routine on the given host with the given name.
        /// </summary>
        static public Routine Find(GameObject inHost, string inName)
        {
            Manager m = Manager.Get();
            if (m != null)
                return m.Fibers.RunQueryFirst(new GameObjectNameQuery() { Host = inHost, Name = inName }, new NullOperation());
            return Routine.Null;
        }

        /// <summary>
        /// Adds currently running routines with the given name to the given collection.
        /// </summary>
        static public void Find(string inName, ref ICollection<Routine> ioRoutines)
        {
            Manager m = Manager.Get();
            if (m != null)
                m.Fibers.RunQueryAll(new NameQuery() { Name = inName }, new NullOperation(), ref ioRoutines);
        }

        /// <summary>
        /// Returns the first currently running routine with the given name.
        /// </summary>
        static public Routine Find(string inName)
        {
            Manager m = Manager.Get();
            if (m != null)
                return m.Fibers.RunQueryFirst(new NameQuery() { Name = inName }, new NullOperation());
            return Routine.Null;
        }

        #endregion

        #region Manual Updates

        /// <summary>
        /// Updates all routines with the Manual update mode.
        /// Note that you cannot nest a ManualUpdate call within a ManualUpdate call.
        /// </summary>
        static public bool ManualUpdate()
        {
            return ManualUpdate(Time.deltaTime);
        }

        /// <summary>
        /// Updates all routines with the Manual update mode with the given delta time.
        /// Note that you cannot nest a ManualUpdate call within a ManualUpdate call.
        /// </summary>
        static public bool ManualUpdate(float inDeltaTime)
        {
            Manager m = Manager.Get();
            if (m != null)
                return m.ManualUpdate(inDeltaTime);
            return false;
        }

        #endregion

        #region Lifecycle

        /// <summary>
        /// Initializes the BeauRoutine system.
        /// This will happen automatically on startup.
        /// </summary>
        static public void Initialize()
        {
            Manager.Create();
        }

        /// <summary>
        /// Shuts down the BeauRoutine system.
        /// Any further calls to BeauRoutine functions will throw an exception
        /// until Initialize() is explicitly called again.
        /// </summary>
        static public void Shutdown()
        {
            Manager.Destroy();
        }

        #endregion

        #region Settings

        /// <summary>
        /// Contains global settings.
        /// </summary>
        static public class Settings
        {
            /// <summary>
            /// BeauRoutine version number.
            /// </summary>
            static public Version Version
            {
                get { return Manager.VERSION; }
            }

            /// <summary>
            /// Sets the maximum number of concurrent routines
            /// before more memory must be allocated to run routines.
            /// </summary>
            static public void SetCapacity(int inCapacity)
            {
                Manager m = Manager.Get();
                if (m != null)
                    m.Fibers.SetCapacity(inCapacity);
            }

            /// <summary>
            /// Enables/disables debug mode.
            /// Debug mode actives additional checks and profiling.
            /// </summary>
            static public bool DebugMode
            {
                get
                {
                    #if DEVELOPMENT
                    Manager m = Manager.Get();
                    if (m != null)
                        return m.DebugMode;
                    #endif // DEVELOPMENT
                    return false;
                }
                set
                {
                    #if DEVELOPMENT
                    Manager m = Manager.Get();
                    if (m != null)
                        m.DebugMode = value;
                    #endif // DEVELOPMENT
                }
            }

            /// <summary>
            /// Enables/disables profiling.
            /// Profiling will capture data about execution time
            /// and periodically log stats to the console.
            /// </summary>
            static public bool ProfilingEnabled
            {
                get
                {
                    #if DEVELOPMENT
                    Manager m = Manager.Get();
                    if (m != null)
                        return m.ProfilingEnabled;
                    #endif // DEVELOPMENT
                    return false;
                }
                set
                {
                    #if DEVELOPMENT
                    Manager m = Manager.Get();
                    if (m != null)
                        m.ProfilingEnabled = value;
                    #endif // DEVELOPMENT
                }
            }

            /// <summary>
            /// Enables/disables exception handling.
            /// By default this is enabled.
            /// </summary>
            static public bool HandleExceptions
            {
                get
                {
                    Manager m = Manager.Get();
                    if (m != null)
                        return m.HandleExceptions;
                    return true;
                }
                set
                {
                    Manager m = Manager.Get();
                    if (m != null)
                        m.HandleExceptions = value;
                }
            }

            /// <summary>
            /// Gets/sets the default phase for instantiated routines.
            /// </summary>
            static public RoutinePhase DefaultPhase
            {
                get
                {
                    Manager m = Manager.Get();
                    if (m != null)
                        return m.DefaultPhase;
                    return RoutinePhase.LateUpdate;
                }
                set
                {
                    Manager m = Manager.Get();
                    if (m != null)
                        m.DefaultPhase = value;
                }
            }

            /// <summary>
            /// Enables/disables snapshot profiling.
            /// Snapshots capture the routines running at the point
            /// when a new high watermark is established for concurrent routines.
            /// This will only function when both Debug Mode and Profiling are enabled.
            /// </summary>
            static public bool SnapshotEnabled
            {
                get
                {
                    Manager m = Manager.Get();
                    if (m != null)
                        return m.SnapshotEnabled;
                    return false;
                }
                set
                {
                    #if DEVELOPMENT
                    Manager m = Manager.Get();
                    if (m != null)
                        m.SnapshotEnabled = value;
                    #endif // DEVELOPMENT
                }
            }

            /// <summary>
            /// Pauses/resumes Routine updates.
            /// </summary>
            static public bool Paused
            {
                get
                {
                    Manager m = Manager.Get();
                    if (m != null)
                        return m.SystemPaused;
                    return false;
                }
                set
                {
                    Manager m = Manager.Get();
                    if (m != null)
                        m.SystemPaused = value;
                }
            }

            /// <summary>
            /// Gets/sets the interval between ThinkUpdate phases.
            /// </summary>
            static public float ThinkUpdateInterval
            {
                get
                {
                    Manager m = Manager.Get();
                    if (m != null)
                        return m.ThinkUpdateInterval;
                    return Manager.DEFAULT_THINKUPDATE_INTERVAL;
                }
                set
                {
                    Manager m = Manager.Get();
                    if (m != null)
                        m.SetThinkUpdateInterval(value);
                }
            }

            /// <summary>
            /// Gets/sets the interval between CustomUpdate phases.
            /// </summary>
            static public float CustomUpdateInterval
            {
                get
                {
                    Manager m = Manager.Get();
                    if (m != null)
                        return m.CustomUpdateInterval;
                    return Manager.DEFAULT_CUSTOMUPDATE_INTERVAL;
                }
                set
                {
                    Manager m = Manager.Get();
                    if (m != null)
                        m.SetCustomUpdateInterval(value);
                }
            }

            /// <summary>
            /// Gets/sets the expected milliseconds budget per frame.
            /// </summary>
            static public double FrameDurationBudgetMS
            {
                get
                {
                    Manager m = Manager.Get();
                    if (m != null)
                        return m.FrameDurationBudgetTicks / TimeSpan.TicksPerMillisecond;
                    return Manager.CalculateDefaultFrameBudgetTicks() / TimeSpan.TicksPerMillisecond;
                }
                set
                {
                    Manager m = Manager.Get();
                    if (m != null)
                    {
                        m.SetFrameBudget(value);
                    }
                }
            }

            /// <summary>
            /// Gets/sets the minimum async milliseconds budget per frame.
            /// </summary>
            static public double AsyncBudgetMinMS
            {
                get
                {
                    Manager m = Manager.Get();
                    if (m != null)
                        return m.AsyncBudgetTicksMin / TimeSpan.TicksPerMillisecond;
                    return Manager.CalculateDefaultFrameBudgetTicks() * Manager.DEFAULT_ASYNC_PERCENTAGE_MIN / TimeSpan.TicksPerMillisecond;
                }
                set
                {
                    Manager m = Manager.Get();
                    if (m != null)
                        m.AsyncBudgetTicksMin = (long) (TimeSpan.TicksPerMillisecond * value);
                }
            }

            /// <summary>
            /// Gets/sets the maximum async milliseconds budget per frame.
            /// </summary>
            static public double AsyncBudgetMaxMS
            {
                get
                {
                    Manager m = Manager.Get();
                    if (m != null)
                        return m.AsyncBudgetTicksMax / TimeSpan.TicksPerMillisecond;
                    return Manager.CalculateDefaultFrameBudgetTicks() * Manager.DEFAULT_ASYNC_PERCENTAGE_MAX / TimeSpan.TicksPerMillisecond;
                }
                set
                {
                    Manager m = Manager.Get();
                    if (m != null)
                        m.AsyncBudgetTicksMax = (long) (TimeSpan.TicksPerMillisecond * value);
                }
            }

            /// <summary>
            /// Gets/sets whether or not to force single-threaded mode for async operations.
            /// </summary>
            static public bool ForceSingleThreaded
            {
                get
                {
                    Manager m = Manager.Get();
                    if (m != null)
                        return m.ForceSingleThreaded;
                    return false;
                }
                set
                {
                    Manager m = Manager.Get();
                    if (m != null)
                        m.ForceSingleThreaded = value;
                }
            }
        }

        #endregion
    }
}


text:
package org.hawkular.inventory.rest;

import java.io.InputStream;
import java.util.Iterator;

import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Produces;
import javax.inject.Inject;

import org.hawkular.inventory.api.Configuration;
import org.hawkular.inventory.api.EmptyInventory;
import org.hawkular.inventory.api.EntityAlreadyExistsException;
import org.hawkular.inventory.api.EntityNotFoundException;
import org.hawkular.inventory.api.Interest;
import org.hawkular.inventory.api.Inventory;
import org.hawkular.inventory.api.Relationships;
import org.hawkular.inventory.api.Tenants;
import org.hawkular.inventory.api.filters.Filter;
import org.hawkular.inventory.api.model.CanonicalPath;
import org.hawkular.inventory.api.model.Entity;
import org.hawkular.inventory.api.model.Tenant;
import org.hawkular.inventory.cdi.Official;

import rx.Observable;

/**
 * @author Lukas Krejci
 * @since 0.1.0
 */
@ApplicationScoped
public class AutoTenantInventoryProducer {

    @Inject
    @Official
    private Inventory inventory;

    @Produces
    @AutoTenant
    @ApplicationScoped
    public Inventory getInventory() {
        return new Inventory() {
            @Override
            public void initialize(Configuration configuration) {
                inventory.initialize(configuration);
            }

            @Override
            public Tenants.ReadWrite tenants() {
                Tenants.ReadWrite actual = inventory.tenants();
                return new Tenants.ReadWrite() {
                    @Override
                    public Tenants.Multiple getAll(Filter[][] filters) {
                        return new EmptyInventory.TenantsMultiple();
                    }

                    @Override
                    public Tenants.Single get(String id) throws EntityNotFoundException {
                        Tenants.Single ret = actual.get(id);
                        if (ret.exists()) {
                            return ret;
                        } else {
                            return actual.create(Tenant.Blueprint.builder().withId(id).build());
                        }
                    }

                    @Override
                    public Tenants.Single create(Tenant.Blueprint blueprint) throws EntityAlreadyExistsException {
                        return actual.create(blueprint);
                    }

                    @Override
                    public void update(String id, Tenant.Update update) throws EntityNotFoundException {
                        actual.update(id, update);
                    }

                    @Override
                    public void delete(String id) throws EntityNotFoundException {
                        actual.delete(id);
                    }
                };
            }

            @Override
            public Relationships.Read relationships() {
                return inventory.relationships();
            }

            @Override
            public boolean hasObservers(Interest<?, ?> interest) {
                return inventory.hasObservers(interest);
            }

            @Override
            public <C, E> Observable<C> observable(Interest<C, E> interest) {
                return inventory.observable(interest);
            }

            @Override
            public InputStream getGraphSON(String tenantId) {
                return inventory.getGraphSON(tenantId);
            }

            @Override
            public <T extends Entity<?, ?>> Iterator<T> getTransitiveClosureOver(CanonicalPath startingPoint,
                                                                                Relationships.Direction direction,
                                                                         Class<T> clazz, String... relationshipNames) {
                return inventory.getTransitiveClosureOver(startingPoint, direction, clazz, relationshipNames);
            }

            @Override
            public void close() throws Exception {
                inventory.close();
            }
        };
    }
}


text:
"""This file contains the Bencode Parser.

Plaso's engine calls BencodeParser when it encounters bencoded files to be
processed, typically seen for BitTorrent data.
"""

import logging
import re
import os

import bencode

from plaso.lib import errors
from plaso.parsers import interface
from plaso.parsers import manager

class BencodeParser(interface.SingleFileBaseParser):
  """Deserializes bencoded file; produces a dictionary containing bencoded data.

  The Plaso engine calls parsers by their Parse() method. The Parse() function
  deserializes bencoded files using the BitTorrent-bencode library and
  calls plugins (BencodePlugin) registered through the interface by their
  Process() to produce event objects.

  Plugins are how this parser understands the content inside a bencoded file,
  each plugin holds logic specific to a particular bencoded file. See the
  bencode_plugins / directory for examples of how bencode plugins are
  implemented.
  """

  _INITIAL_FILE_OFFSET = None

  # Regex match for a bencode dictionary followed by a field size.
  BENCODE_RE = re.compile(r'd[0-9]')

  NAME = u'bencode'
  DESCRIPTION = u'Parser for bencoded files.'

  _plugin_classes = {}

  def __init__(self):
    """Initializes a parser object."""
    super(BencodeParser, self).__init__()
    self._plugins = BencodeParser.GetPluginObjects()

  def ParseFileObject(self, parser_mediator, file_object, **kwargs):
    """Parses a bencoded file-like object.

    Args:
      parser_mediator: A parser mediator object (instance of ParserMediator).
      file_object: A file-like object.

    Raises:
      UnableToParseFile: when the file cannot be parsed.
    """
    file_object.seek(0, os.SEEK_SET)
    header = file_object.read(2)
    if not self.BENCODE_RE.match(header):
      raise errors.UnableToParseFile(u'Not a valid Bencoded file.')

    file_object.seek(0, os.SEEK_SET)
    try:
      data_object = bencode.bdecode(file_object.read())

    except (IOError, bencode.BTFailure) as exception:
      raise errors.UnableToParseFile(
          u'[{0:s}] unable to parse file: {1:s} with error: {2:s}'.format(
              self.NAME, parser_mediator.GetDisplayName(), exception))

    if not data_object:
      raise errors.UnableToParseFile(
          u'[{0:s}] missing decoded data for file: {1:s}'.format(
              self.NAME, parser_mediator.GetDisplayName()))

    for plugin_object in self._plugins:
      try:
        plugin_object.UpdateChainAndProcess(parser_mediator, data=data_object)
      except errors.WrongBencodePlugin as exception:
        logging.debug(u'[{0:s}] wrong plugin: {1:s}'.format(
            self.NAME, exception))

manager.ParsersManager.RegisterParser(BencodeParser)


text:
# --- !Ups

create table my_group (
  id                        bigint not null,
  name                      varchar(255),
  owner                     varchar(255),
  members                   varchar(255),
  constraint pk_my_group primary key (id))
;

create table person (
  id                        bigint not null,
  email                     varchar(255),
  fullname                  varchar(255),
  webservice_token          varchar(255),
  confirmation_token        varchar(255),
  password_hash             varchar(255),
  date_creation             timestamp,
  validated                 boolean,
  constraint uq_person_email unique (email),
  constraint pk_person primary key (id))
;

create table template (
  id                        bigint not null,
  name                      varchar(255),
  html                      TEXT,
  parameters                varchar(255),
  owner                     varchar(255),
  groups                    varchar(255),
  constraint pk_template primary key (id))
;

create table token (
  token                     varchar(255) not null,
  user_id                   bigint,
  type                      varchar(8),
  date_creation             timestamp,
  email                     varchar(255),
  constraint ck_token_type check (type in ('password','email')),
  constraint pk_token primary key (token))
;

create sequence my_group_seq;

create sequence person_seq;

create sequence template_seq;

create sequence token_seq;

# --- !Downs

SET REFERENTIAL_INTEGRITY FALSE;

drop table if exists my_group;

drop table if exists person;

drop table if exists template;

drop table if exists token;

SET REFERENTIAL_INTEGRITY TRUE;

drop sequence if exists my_group_seq;

drop sequence if exists person_seq;

drop sequence if exists template_seq;

drop sequence if exists token_seq;


text:
var gulp = require('gulp');
var plugins = require('gulp-load-plugins')({lazy: false});
var config = require('./config');

gulp.task('copy-media', function () {
  return gulp.src(config.mediaSrc)
    .pipe(plugins.plumber())
    .pipe(gulp.dest(config.distPath));
});


text:
#ifndef __vec4_h__
#define __vec4_h__

#include "kode.h"
#include "utility.h"

struct kmMat4;

#pragma pack(push)  /* push current alignment to stack */
#pragma pack(1)     /* set alignment to 1 byte boundary */

typedef struct kmVec4
{
    kmScalar x;
    kmScalar y;
    kmScalar z;
    kmScalar w;
} kmVec4;

#pragma pack(pop)

kmVec4*  kmVec4Fill ( kmVec4* pOut, kmScalar x, kmScalar y, kmScalar z, kmScalar w );
kmVec4*  kmVec4Add ( kmVec4* pOut, const kmVec4* pV1, const kmVec4* pV2 );
kmScalar kmVec4Dot ( const kmVec4* pV1, const kmVec4* pV2 );
kmScalar kmVec4Length ( const kmVec4* pIn );
kmScalar kmVec4LengthSq ( const kmVec4* pIn );
kmVec4*  kmVec4Lerp ( kmVec4* pOut, const kmVec4* pV1, const kmVec4* pV2, kmScalar t );
kmVec4*  kmVec4Normalize ( kmVec4* pOut, const kmVec4* pIn );
kmVec4*  kmVec4Scale ( kmVec4* pOut, const kmVec4* pIn, const kmScalar s ); ///< Scales a vector to length s
kmVec4*  kmVec4Subtract ( kmVec4* pOut, const kmVec4* pV1, const kmVec4* pV2 );
kmVec4*  kmVec4Transform ( kmVec4* pOut, const kmVec4* pV, const struct kmMat4* pM );
kmVec4*  kmVec4TransformArray ( kmVec4* pOut, unsigned int outStride, const kmVec4* pV, unsigned int vStride, const struct kmMat4* pM, unsigned int count );
int      kmVec4AreEqual ( const kmVec4* p1, const kmVec4* p2 );
kmVec4*  kmVec4Assign ( kmVec4* pOut, const kmVec4* pIn );

#endif // __vec4_h__


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

  <xi:include href="prefs.html" />

    <title>Syntax Highlighting</title>

    <link py:for="style in sorted(styles)" rel="stylesheet" type="text/css"
          href="${href.pygments('%s.css' % style)}" title="${style.title()}" />

The Pygments syntax highlighter can be used with
      different coloring styles.

Style:
        <select id="pygment_theme" name="style">
          <option py:for="style in sorted(styles)" value="${style}"
                  selected="${selection == style or None}">${style.title()}</option>
        </select>

      Preview:

${output}


text:
package main

import (
	"bytes"
	"encoding/json"
	"flag"
	"fmt"
	"os"
	"os/exec"
	"path"
	"strconv"
	"strings"
	"sync"
	"syscall"
	"time"
)

// TODO(davidben): Link tests with the malloc shim and port -malloc-test to this runner.

var (
	useValgrind     = flag.Bool("valgrind", false, "If true, run code under valgrind")
	useCallgrind    = flag.Bool("callgrind", false, "If true, run code under valgrind to generate callgrind traces.")
	useGDB          = flag.Bool("gdb", false, "If true, run BoringSSL code under gdb")
	buildDir        = flag.String("build-dir", "build", "The build directory to run the tests from.")
	numWorkers      = flag.Int("num-workers", 1, "Runs the given number of workers when testing.")
	jsonOutput      = flag.String("json-output", "", "The file to output JSON results to.")
	mallocTest      = flag.Int64("malloc-test", -1, "If non-negative, run each test with each malloc in turn failing from the given number onwards.")
	mallocTestDebug = flag.Bool("malloc-test-debug", false, "If true, ask each test to abort rather than fail a malloc. This can be used with a specific value for --malloc-test to identity the malloc failing that is causing problems.")
)

type test []string

type result struct {
	Test   test
	Passed bool
	Error  error
}

// testOutput is a representation of Chromium's JSON test result format. See
// https://www.chromium.org/developers/the-json-test-results-format
type testOutput struct {
	Version           int                   `json:"version"`
	Interrupted       bool                  `json:"interrupted"`
	PathDelimiter     string                `json:"path_delimiter"`
	SecondsSinceEpoch float64               `json:"seconds_since_epoch"`
	NumFailuresByType map[string]int        `json:"num_failures_by_type"`
	Tests             map[string]testResult `json:"tests"`
}

type testResult struct {
	Actual       string `json:"actual"`
	Expected     string `json:"expected"`
	IsUnexpected bool   `json:"is_unexpected"`
}

func newTestOutput() *testOutput {
	return &testOutput{
		Version:           3,
		PathDelimiter:     ".",
		SecondsSinceEpoch: float64(time.Now().UnixNano()) / float64(time.Second/time.Nanosecond),
		NumFailuresByType: make(map[string]int),
		Tests:             make(map[string]testResult),
	}
}

func (t *testOutput) addResult(name, result string) {
	if _, found := t.Tests[name]; found {
		panic(name)
	}
	t.Tests[name] = testResult{
		Actual:       result,
		Expected:     "PASS",
		IsUnexpected: result != "PASS",
	}
	t.NumFailuresByType[result]++
}

func (t *testOutput) writeTo(name string) error {
	file, err := os.Create(name)
	if err != nil {
		return err
	}
	defer file.Close()
	out, err := json.MarshalIndent(t, "", "  ")
	if err != nil {
		return err
	}
	_, err = file.Write(out)
	return err
}

func valgrindOf(dbAttach bool, path string, args ...string) *exec.Cmd {
	valgrindArgs := []string{"--error-exitcode=99", "--track-origins=yes", "--leak-check=full"}
	if dbAttach {
		valgrindArgs = append(valgrindArgs, "--db-attach=yes", "--db-command=xterm -e gdb -nw %f %p")
	}
	valgrindArgs = append(valgrindArgs, path)
	valgrindArgs = append(valgrindArgs, args...)

	return exec.Command("valgrind", valgrindArgs...)
}

func callgrindOf(path string, args ...string) *exec.Cmd {
	valgrindArgs := []string{"-q", "--tool=callgrind", "--dump-instr=yes", "--collect-jumps=yes", "--callgrind-out-file=" + *buildDir + "/callgrind/callgrind.out.%p"}
	valgrindArgs = append(valgrindArgs, path)
	valgrindArgs = append(valgrindArgs, args...)

	return exec.Command("valgrind", valgrindArgs...)
}

func gdbOf(path string, args ...string) *exec.Cmd {
	xtermArgs := []string{"-e", "gdb", "--args"}
	xtermArgs = append(xtermArgs, path)
	xtermArgs = append(xtermArgs, args...)

	return exec.Command("xterm", xtermArgs...)
}

type moreMallocsError struct{}

func (moreMallocsError) Error() string {
	return "child process did not exhaust all allocation calls"
}

var errMoreMallocs = moreMallocsError{}

func runTestOnce(test test, mallocNumToFail int64) (passed bool, err error) {
	prog := path.Join(*buildDir, test[0])
	args := test[1:]
	var cmd *exec.Cmd
	if *useValgrind {
		cmd = valgrindOf(false, prog, args...)
	} else if *useCallgrind {
		cmd = callgrindOf(prog, args...)
	} else if *useGDB {
		cmd = gdbOf(prog, args...)
	} else {
		cmd = exec.Command(prog, args...)
	}
	var stdoutBuf bytes.Buffer
	var stderrBuf bytes.Buffer
	cmd.Stdout = &stdoutBuf
	cmd.Stderr = &stderrBuf
	if mallocNumToFail >= 0 {
		cmd.Env = os.Environ()
		cmd.Env = append(cmd.Env, "MALLOC_NUMBER_TO_FAIL="+strconv.FormatInt(mallocNumToFail, 10))
		if *mallocTestDebug {
			cmd.Env = append(cmd.Env, "MALLOC_ABORT_ON_FAIL=1")
		}
		cmd.Env = append(cmd.Env, "_MALLOC_CHECK=1")
	}

	if err := cmd.Start(); err != nil {
		return false, err
	}
	if err := cmd.Wait(); err != nil {
		if exitError, ok := err.(*exec.ExitError); ok {
			if exitError.Sys().(syscall.WaitStatus).ExitStatus() == 88 {
				return false, errMoreMallocs
			}
		}
		fmt.Print(string(stderrBuf.Bytes()))
		return false, err
	}
	fmt.Print(string(stderrBuf.Bytes()))

	// Account for Windows line-endings.
	stdout := bytes.Replace(stdoutBuf.Bytes(), []byte("\r\n"), []byte("\n"), -1)

	if bytes.HasSuffix(stdout, []byte("PASS\n")) &&
		(len(stdout) == 5 || stdout[len(stdout)-6] == '\n') {
		return true, nil
	}
	return false, nil
}

func runTest(test test) (bool, error) {
	if *mallocTest < 0 {
		return runTestOnce(test, -1)
	}

	for mallocNumToFail := int64(*mallocTest); ; mallocNumToFail++ {
		if passed, err := runTestOnce(test, mallocNumToFail); err != errMoreMallocs {
			if err != nil {
				err = fmt.Errorf("at malloc %d: %s", mallocNumToFail, err)
			}
			return passed, err
		}
	}
}

// shortTestName returns the short name of a test. Except for evp_test, it
// assumes that any argument which ends in .txt is a path to a data file and not
// relevant to the test's uniqueness.
func shortTestName(test test) string {
	var args []string
	for _, arg := range test {
		if test[0] == "crypto/evp/evp_test" || !strings.HasSuffix(arg, ".txt") {
			args = append(args, arg)
		}
	}
	return strings.Join(args, " ")
}

// setWorkingDirectory walks up directories as needed until the current working
// directory is the top of a BoringSSL checkout.
func setWorkingDirectory() {
	for i := 0; i < 64; i++ {
		if _, err := os.Stat("BUILDING.md"); err == nil {
			return
		}
		os.Chdir("..")
	}

	panic("Couldn't find BUILDING.md in a parent directory!")
}

func parseTestConfig(filename string) ([]test, error) {
	in, err := os.Open(filename)
	if err != nil {
		return nil, err
	}
	defer in.Close()

	decoder := json.NewDecoder(in)
	var result []test
	if err := decoder.Decode(&result); err != nil {
		return nil, err
	}
	return result, nil
}

func worker(tests <-chan test, results chan<- result, done *sync.WaitGroup) {
	defer done.Done()
	for test := range tests {
		passed, err := runTest(test)
		results <- result{test, passed, err}
	}
}

func main() {
	flag.Parse()
	setWorkingDirectory()

	testCases, err := parseTestConfig("util/all_tests.json")
	if err != nil {
		fmt.Printf("Failed to parse input: %s\n", err)
		os.Exit(1)
	}

	var wg sync.WaitGroup
	tests := make(chan test, *numWorkers)
	results := make(chan result, *numWorkers)

	for i := 0; i < *numWorkers; i++ {
		wg.Add(1)
		go worker(tests, results, &wg)
	}

	go func() {
		for _, test := range testCases {
			tests <- test
		}
		close(tests)

		wg.Wait()
		close(results)
	}()

	testOutput := newTestOutput()
	var failed []test
	for testResult := range results {
		test := testResult.Test

		fmt.Printf("%s\n", strings.Join([]string(test), " "))
		name := shortTestName(test)
		if testResult.Error != nil {
			fmt.Printf("%s failed to complete: %s\n", test[0], testResult.Error)
			failed = append(failed, test)
			testOutput.addResult(name, "CRASHED")
		} else if !testResult.Passed {
			fmt.Printf("%s failed to print PASS on the last line.\n", test[0])
			failed = append(failed, test)
			testOutput.addResult(name, "FAIL")
		} else {
			testOutput.addResult(name, "PASS")
		}
	}

	if *jsonOutput != "" {
		if err := testOutput.writeTo(*jsonOutput); err != nil {
			fmt.Fprintf(os.Stderr, "Error: %s\n", err)
		}
	}

	if len(failed) > 0 {
		fmt.Printf("\n%d of %d tests failed:\n", len(failed), len(testCases))
		for _, test := range failed {
			fmt.Printf("\t%s\n", strings.Join([]string(test), " "))
		}
		os.Exit(1)
	}

	fmt.Printf("\nAll tests passed!\n")
}


text:
from . import util
import imp
import importlib
from importlib import machinery
import sys
from test import support
import types
import unittest

class ImportModuleTests(unittest.TestCase):

    """Test importlib.import_module."""

    def test_module_import(self):
        # Test importing a top-level module.
        with util.mock_modules('top_level') as mock:
            with util.import_state(meta_path=[mock]):
                module = importlib.import_module('top_level')
                self.assertEqual(module.__name__, 'top_level')

    def test_absolute_package_import(self):
        # Test importing a module from a package with an absolute name.
        pkg_name = 'pkg'
        pkg_long_name = '{0}.__init__'.format(pkg_name)
        name = '{0}.mod'.format(pkg_name)
        with util.mock_modules(pkg_long_name, name) as mock:
            with util.import_state(meta_path=[mock]):
                module = importlib.import_module(name)
                self.assertEqual(module.__name__, name)

    def test_shallow_relative_package_import(self):
        # Test importing a module from a package through a relative import.
        pkg_name = 'pkg'
        pkg_long_name = '{0}.__init__'.format(pkg_name)
        module_name = 'mod'
        absolute_name = '{0}.{1}'.format(pkg_name, module_name)
        relative_name = '.{0}'.format(module_name)
        with util.mock_modules(pkg_long_name, absolute_name) as mock:
            with util.import_state(meta_path=[mock]):
                importlib.import_module(pkg_name)
                module = importlib.import_module(relative_name, pkg_name)
                self.assertEqual(module.__name__, absolute_name)

    def test_deep_relative_package_import(self):
        modules = ['a.__init__', 'a.b.__init__', 'a.c']
        with util.mock_modules(*modules) as mock:
            with util.import_state(meta_path=[mock]):
                importlib.import_module('a')
                importlib.import_module('a.b')
                module = importlib.import_module('..c', 'a.b')
                self.assertEqual(module.__name__, 'a.c')

    def test_absolute_import_with_package(self):
        # Test importing a module from a package with an absolute name with
        # the 'package' argument given.
        pkg_name = 'pkg'
        pkg_long_name = '{0}.__init__'.format(pkg_name)
        name = '{0}.mod'.format(pkg_name)
        with util.mock_modules(pkg_long_name, name) as mock:
            with util.import_state(meta_path=[mock]):
                importlib.import_module(pkg_name)
                module = importlib.import_module(name, pkg_name)
                self.assertEqual(module.__name__, name)

    def test_relative_import_wo_package(self):
        # Relative imports cannot happen without the 'package' argument being
        # set.
        with self.assertRaises(TypeError):
            importlib.import_module('.support')

    def test_loaded_once(self):
        # Issue #13591: Modules should only be loaded once when
        # initializing the parent package attempts to import the
        # module currently being imported.
        b_load_count = 0
        def load_a():
            importlib.import_module('a.b')
        def load_b():
            nonlocal b_load_count
            b_load_count += 1
        code = {'a': load_a, 'a.b': load_b}
        modules = ['a.__init__', 'a.b']
        with util.mock_modules(*modules, module_code=code) as mock:
            with util.import_state(meta_path=[mock]):
                importlib.import_module('a.b')
        self.assertEqual(b_load_count, 1)

class FindLoaderTests(unittest.TestCase):

    class FakeMetaFinder:
        @staticmethod
        def find_module(name, path=None): return name, path

    def test_sys_modules(self):
        # If a module with __loader__ is in sys.modules, then return it.
        name = 'some_mod'
        with util.uncache(name):
            module = imp.new_module(name)
            loader = 'a loader!'
            module.__loader__ = loader
            sys.modules[name] = module
            found = importlib.find_loader(name)
            self.assertEqual(loader, found)

    def test_sys_modules_loader_is_None(self):
        # If sys.modules[name].__loader__ is None, raise ValueError.
        name = 'some_mod'
        with util.uncache(name):
            module = imp.new_module(name)
            module.__loader__ = None
            sys.modules[name] = module
            with self.assertRaises(ValueError):
                importlib.find_loader(name)

    def test_success(self):
        # Return the loader found on sys.meta_path.
        name = 'some_mod'
        with util.uncache(name):
            with util.import_state(meta_path=[self.FakeMetaFinder]):
                self.assertEqual((name, None), importlib.find_loader(name))

    def test_success_path(self):
        # Searching on a path should work.
        name = 'some_mod'
        path = 'path to some place'
        with util.uncache(name):
            with util.import_state(meta_path=[self.FakeMetaFinder]):
                self.assertEqual((name, path),
                                 importlib.find_loader(name, path))

    def test_nothing(self):
        # None is returned upon failure to find a loader.
        self.assertIsNone(importlib.find_loader('nevergoingtofindthismodule'))

class InvalidateCacheTests(unittest.TestCase):

    def test_method_called(self):
        # If defined the method should be called.
        class InvalidatingNullFinder:
            def __init__(self, *ignored):
                self.called = False
            def find_module(self, *args):
                return None
            def invalidate_caches(self):
                self.called = True

        key = 'gobledeegook'
        meta_ins = InvalidatingNullFinder()
        path_ins = InvalidatingNullFinder()
        sys.meta_path.insert(0, meta_ins)
        self.addCleanup(lambda: sys.path_importer_cache.__delitem__(key))
        sys.path_importer_cache[key] = path_ins
        self.addCleanup(lambda: sys.meta_path.remove(meta_ins))
        importlib.invalidate_caches()
        self.assertTrue(meta_ins.called)
        self.assertTrue(path_ins.called)

    def test_method_lacking(self):
        # There should be no issues if the method is not defined.
        key = 'gobbledeegook'
        sys.path_importer_cache[key] = imp.NullImporter('abc')
        self.addCleanup(lambda: sys.path_importer_cache.__delitem__(key))
        importlib.invalidate_caches()  # Shouldn't trigger an exception.

class FrozenImportlibTests(unittest.TestCase):

    def test_no_frozen_importlib(self):
        # Should be able to import w/o _frozen_importlib being defined.
        module = support.import_fresh_module('importlib', blocked=['_frozen_importlib'])
        self.assertFalse(isinstance(module.__loader__,
                                    machinery.FrozenImporter))

class StartupTests(unittest.TestCase):

    def test_everyone_has___loader__(self):
        # Issue #17098: all modules should have __loader__ defined.
        for name, module in sys.modules.items():
            if isinstance(module, types.ModuleType):
                if name in sys.builtin_module_names:
                    self.assertEqual(importlib.machinery.BuiltinImporter,
                                     module.__loader__)
                elif imp.is_frozen(name):
                    self.assertEqual(importlib.machinery.FrozenImporter,
                                     module.__loader__)

def test_main():
    from test.support import run_unittest
    run_unittest(ImportModuleTests,
                 FindLoaderTests,
                 InvalidateCacheTests,
                 FrozenImportlibTests,
                 StartupTests)

if __name__ == '__main__':
    test_main()


text:
(function($, $J) {
  if($J)
    $ = $J;
  function generatePagination(currentPage, elements, perPage) {
    let html = '';
    let totalPages = Math.ceil(elements.length / perPage);
    if (totalPages <= 1)
      return '';
    if (currentPage > 1)
      html += '<button type="button" class="pagination-navprev btnv6_blue_hoverfade" data-i18n="pagination_button_prev">< prev</button>';
    if(currentPage !== 1)
      html += '<button type="button" class="btnv6_blue_hoverfade">1</button>';
    else
      html += '1';
    if(currentPage === 5)
      html += '<button type="button" class="btnv6_blue_hoverfade">2</button>';
    if (currentPage > 2) {
      if(currentPage > 5)
        html += '...';
      if (currentPage > 3)
        html += '<button type="button" class="btnv6_blue_hoverfade">' + (currentPage - 2) + '</button>';
      html += '<button type="button" class="btnv6_blue_hoverfade">' + (currentPage - 1) + '</button>';
    }
    if (currentPage !== 1 && currentPage !== totalPages)
      html += '' + currentPage + '';
    if (currentPage < totalPages - 1) {
      html += '<button type="button" class="btnv6_blue_hoverfade">' + (currentPage + 1) + '</button>';
      if (currentPage < totalPages - 2)
        html += '<button type="button" class="btnv6_blue_hoverfade">' + (currentPage + 2) + '</button>';
      if(currentPage < totalPages - 4)
        html += '...';
    }
    if(currentPage === totalPages - 4)
      html += '<button type="button" class="btnv6_blue_hoverfade">' + (totalPages - 1) + '</button>';
    if(currentPage !== totalPages)
      html += '<button type="button" class="btnv6_blue_hoverfade">' + totalPages + '</button>';
    else
      html += '' + totalPages + '';
    if (currentPage < totalPages)
      html += '<button type="button" class="pagination-navnext btnv6_blue_hoverfade" data-i18n="pagination_button_next">next ></button>';
    return html;
  }

  /**
   * @name PaginationPluginParams
   * @property {number} currentPage
   * @property {object[]} elements
   * @property {number} perPage Amount of items displayed per page
   * @property {object} languageData Object containing translated strings
   */
  /**
   * @param {PaginationPluginParams} obj
   */
  $.fn.pagination = function(obj) {
    let html = generatePagination(obj.currentPage, obj.elements, obj.perPage);
    let $this = $(this);
    $this
      .off('click')
      .on('click', 'button', function() {
        let $inner = $(this);
        let newPage = $inner.text();
        if ($inner.hasClass('pagination-navprev'))
          obj.currentPage--;
        else if ($inner.hasClass('pagination-navnext'))
          obj.currentPage++;
        else
          obj.currentPage = +newPage;
        let html = generatePagination(obj.currentPage, obj.elements, obj.perPage);
        $this.html(html);
        if(i18nDOM && obj.languageData) {
          i18nDOM.nonchrome('data-i18n', obj.languageData);
        }
        obj.change(obj.currentPage);
      })
      .html(html);
    if(i18nDOM && obj.languageData) {
      i18nDOM.nonchrome('data-i18n', obj.languageData);
    }
  };
})(jQuery, window.$J);